Flask is a python module that that makes Web application creation easier. Flask generates Web pages on the fly, and when coupled with WSGI (Web Server Gateway Interface) on an Apache Web server, scales up to commercial usage. Flask is built on the WSGI Werkzeug toolkit and the Jinja2 template engine.
The definitive Flask tutorial: Flask Mega Tutorial.
A readable and to-the-point WSGI installation guide: How to deploy a Flask application on Ubuntu.
This is a concise reminder guide taken from the above. See the above references for specific details.
Installing mod_wsgi
You can install all required mod_wsgi components on Ubuntu Unix (typical AWS implementation) with:
sudo apt-get install apache2 apache2-utils libexpat1 ssl-cert python
Use the curl command to verify the Apache server is responding:
curl http://localhost
You should see the default Ubuntu Apache page.
Install mod_wsgi with:
sudo apt-get install libapache2-mod-wsgi
Restart Apache service.
sudo /etc/init.d/apache2 restart
Creating the WSGI Website
To serve the python application, Apache needs to forward requests to mod_wsgi. Create a website for WSGI that tells Apache the location of the python WSGI configuration file:
sudo nano /etc/apache2/conf-available/wsgi.conf
Add the following line:
WSGIScriptAlias /test_wsgi /var/www/html/test_wsgi.py
Next, create a python test script that corresponds to the WSGIScriptAlias above.
sudo nano /var/www/html/test_wsgi.py
Add the following lines:
def application(environ,start_response):
status = '200 OK'
html = '\n' \ '\n' \ '\n' \ 'mod_wsgi Test Page\n' \ '\n' \ '\n' \ '\n'
response_header = [('Content-type','text/html')]
start_response(status,response_header)
return [html]
When you are finished save and close the file.
Once you are done with it, you will need to enable the WSGI configuration and restart Apache.
sudo a2enconf wsgi
sudo /etc/init.d/apache2 restart
Try it out!
http://yoursitename.com/test_wsgi
If you get a 500 Server error and an Apache error log entry:
“TypeError: sequence of byte string values expected, value of type str found”
then for Python 3, the sample app needs to provide byte rather than str for the output string:
def application(environ,start_response):
status = '200 OK'
html = b'\n' \ b'\n' \ b'\n' \ b'mod_wsgi Test Page\n' \ b'\n' \ b'\n' \ b'\n'
response_header = [('Content-type','text/html')]
start_response(status,response_header)
return [html]