Using WSGI

Overview

Python applications can be launched using Passenger offering improved throughput and lifecycle management. Launching CGI scripts wrapped by pyenv will yield very poor throughput as a result of multiple shell subprocesses necessary to ascertain the correct Python interpreter. Adapting a CGI application to WSGI improves throughput significantly by reducing overhead through a persistent process. Pages load quickly, and applications utilize resources efficiently.

Note: This KB requires a v6+ hosting platform.

Simple WSGI script

Prerequisite: First, follow the guide in Using multiple versions with Passenger to create a suitable directory structure.

Create a Passenger-compatible WSGI script named passenger_wsgi.py beneath the public/ folder. A single function, similar to main() in a C application, named application() is the entry-point for Passenger. Without this function and named file, Passenger cannot load your application. The below example is compatible with Python 3:

# Python 3-compatible version
import sys
ctr=0

def application(environ, start_response):
 global ctr
 start_response('200 OK', [('Content-Type', 'text/plain')])
 v = sys.version_info
 ctr+=1
 str = 'hello world from %d.%d.%d!\n' % (v.major, v.minor, v.micro)
 return [bytes(str, 'UTF-8')]

Your directory structure should now look like:

.
├── passenger_wsgi.py
├── public/
├── .python-version
└── tmp/

.python-version is a file created by defining a Python version for the directory, e.g. pyenv local 3.3.5. Connect the public/ folder to a subdomain within the control panel under Web > Subdomains.

Application didn’t launch?

Check the Passenger launcher error log under /var/log/httpd/passenger.log. This is a combined logfile, so always remember to publish coherent, and flawless code!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.