Saturday, 31 July 2010

Production Flask app on CENTOS and Apache via mod_wsgi

Flask is a Python web framework which embraces simplicity and seems to work. It is based on Werkzeug so it is a WSGI application.

I've had some luck in the past using mod_wsgi to run Django apps, so I suspect getting a Flask app to run will be similar.

Using Google, I found the following in the Werkzeug Docs, which I reviewed for the following steps:

1. Install python2.7, mod_wsgi and Flask on production server.

Using Centos 5.4 (unbranded RHEL) comes with with python 2.4 and apache 2.2. Centos (and RHEL) use Python extensively under the hood (for Yum, among other things). I want to use a later version of Python, but one may not simply "upgrade" the version of Python- without breaking the OS - you need to install an additional version. I followed the steps in this guide, under the head "Install Python":
I chose to use Python 2.7 as its the last stable release of Python 2, and I don't intend going Python 3.* for a while. I hope I don't regret that. I needed to change a few things in obvious places as the guide covers Python 2.6.

Next I carried out the steps labelled "Install Setuptools" as this is necessary.

Next I carried out the steps labelled "Install mod_wsgi", restarted httpd and it started!

To install Flask I ran SetupTools explicitly from the location inside of /opt/python2.7/ to install 'pip' into the 2.7 Python distribution. Next I added an alias to pip to the ~/.bash_profile in the same way this was done for the python binary in the VenkysBlog page. Finally I used the source command to load the alias and ran:

pip install Flask

2. Create an appropriate wsgi file.

WSGI uses a file with the extension .wsgi as the interface between the wsgi container (in this case Apache / mod_wsgi) and the app. Flask has excellent documentation:

Steps are as follows:

  1. Place Flask application in a subfolder of the webroot (for testing I just used the "Flask is Fun" example:
  2. Make a file called 'yourapp.wsgi' in the same structure - this is written in Python syntax - here you need to import your app and bind it to the name 'application'. mod_wsgi will then call this object in the appropriate way.

3. Edit apache configuration to invoke wsgi application.

Finally some directives need adding to httpd.conf. The LoadModule statement was added as part of step 1, however the wsgi file need to be referenced vs. the appropriate virtual root.

Great so everything worked! Wasn't that easy?

No comments:

Post a Comment