To host a Flask or a Django applications, I find it very difficult to deploy it to a production server. For example most of the tutorials that i have found in the internet only showing to host a python application running on port (www.example.com:8083) like this. But cPanel provide us a complex free solution to easily host a Flask applications. Lets start now.
Lets start with step by step solutions. Firstly go to your cPanel account. Click on Setup Python App.
Create Application
- Select Latest Python Version.
- Then add Application Root to your domain name path.
- Select Application URL
After creating the application. copy below generated code by just clicking the highlighted part.
Now go to the terminal. (Note: Terminal option must be enabled)
Now add the given code below.
Now paste the code below and press enter.
pip install flask
Now try to check your domain whether it is working or not. If 503 error code shows. Then please add below code to .htaccess file.
RewriteEngine on
RewriteRule ^http://%{HTTP_HOST}%{REQUEST_URI} [END,NE]
Now update pre generated passenger_wsgi.py file with below given code.
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from mainapp import app as application
To test our flask application is working or not update below code.
from flask import Flask, jsonify
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/')
def index():
return '<h1>Web App with Python Flask!</h1>'
After updating the code. Go to python app and restart the server. After restarting we will be able to get this output.
Note: If you are having any problem with the steps. please delete virtualenv file and delete from the python app setup and restart the process.