Flask Snippets

Deploying a Flask app on Webfaction

Posted by esaurito on 2011-08-11 @ 09:08 and filed in Deployment

Webfaction is a Python friendly hosting with affordable pricing and tons of useful features.

To deploy a Flask application on Webfaction you should follow these steps:

|-- apache2
|   |-- bin
|   |-- conf
|   |-- lib
|   |-- logs
|   `-- modules
`-- htdocs
foo@bar:~$ easy_install-2.6 Flask

Note that Webfaction gives you different easy_install executables: use the one that meets the Python version you choose when the application was created.

from yourapp import app as application
WSGIPythonPath /home/yourusername/webapps/yourapp/htdocs/
#If you do not specify the following directive the app *will* work but you will
#see index.py in the path of all URLs
WSGIScriptAlias / /home/yourusername/webapps/yourapp/htdocs/index.py

<Directory /home/yourusername/webapps/yourapp/htdocs/>
   AddHandler wsgi-script .py
   RewriteEngine on
   RewriteBase /
   WSGIScriptReloading On

If you have choosed / as the mout point for your application you are done. If you mounted the application somewhere else (i.e. /blog) there is some additional work to do.

You need to write a WSGI middleware that prefixes SCRIPT_NAME with that prefix otherwise the url_for function will not be able to create the correct URLs for you (the following snippets is kindly provided by Armin himself).

class WebFactionMiddleware(object):
    def __init__(self, app):
        self.app = app
    def __call__(self, environ, start_response):
        environ['SCRIPT_NAME'] = '/yourapp'
        return self.app(environ, start_response)

app.wsgi_app = WebFactionMiddleware(app.wsgi_app)

You can put this snippet in the application's __init__.py.

Happy Flasking!

This snippet by esaurito can be used freely for anything you like. Consider it public domain.