Python apps with Phusion Passenger: Flask example

2015-07-28 · 1 min read

Running Python application with Phusion Passenger may be tricky. This article shows how to deploy a simple Flask to be run by Passenger with a properly set virtual environment.

Let's create a simple Flask application as

from flask import Flask

app = Flask(__name__)

def index():
    return 'Hello World in Flask'

if __name__ == "__main__":

Check if it works

$ python
* Running on (Press CTRL+C to quit)

In a separate window

$ curl localhost:5000
Hello World in Flask

Create in the root of your project.

import sys, os
from web import app as application

HOME = os.environ.get('HOME')

VENV = HOME + '/.venv/app-virtual-env'
PYTHON_BIN = VENV + '/bin/python3'

if sys.executable != PYTHON_BIN:
    os.execl(PYTHON_BIN, PYTHON_BIN, *sys.argv)

sys.path.insert(0, '{v}/lib/python3.5/site-packages'.format(v=VENV))

Virtual environments are stored in $HOME/.venv with app-virtual-env specified as the one to be used by Phussion Passenger while running this application.

Create public/ directory in the root of your application and adjust the Nginx configuration with proper values for server_name and root.

server {
  listen 80;

  root /path/to/your/app/public;

  passenger_enabled on;