This guide covers installing and configuring Flask to run on Apache on Ubuntu. Why would you want to do this? In a nutshell, you want to run Python code in a web environment.
Prerequisites:
- AWS EC2 running Ubuntu Server 14
Instructions:
Installing the software
SSH onto your EC2 instance and run the following commands.
This will install and enable the following components to get everything:
sudo su
apt-get update
apt-get install apache2 python-pip libapache2-mod-wsgi
pip install Flask
Setting up a test program
Create a directory called Flask under /var/www
mkdir /var/www/flask
Create the file /var/www/flask/webtool.py with the following contents
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
app.run()
Next create the file /var/www/flask/webtool.wsgi with following contents
import sys
sys.path.append('/var/www/flask')
from webtool import app as application
Configuring Apache
Edit the following /etc/apache2/sites-available/000-default.conf and insert the following content between the virtual host tags. This will instruct Apache to start a daemon that will interact with Python when URL requests are sent to http://<IP Address of Server>/flask
WSGIDaemonProcess webtool user=ubuntu group=ubuntu threads=5 home=/var/www/flask/
WSGIScriptAlias /flask /var/www/flask/webtool.wsgi
<directory /var/www/flask>
WSGIProcessGroup webtool
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Order deny,allow
Allow from all
</directory>
Restart Apache
service apache2 restart
Testing
Using your web browser go to the following URL http://<IP Address of Server>/flask
All going well you should see the following web page and our faithful friend “Hello world!”
Source: OptimalBI
Troubleshooting
The first place to check will be the apache log files. By default, they can be found here /var/log/apache2/ check the error.log file for any useful information.
The second suggestion I would have is to make sure that the user and group used in the Apache configuration is a valid user and group. if not change them to valid values
WSGIDaemonProcess webtool user=ubuntu group=ubuntu threads=5 home=/var/www/flask/
All the code, all the fun – Ben