Werkzeug

The Swiss Army Knife For Python Web Developers

Serving WSGI Applications

There are many ways to serve a WSGI application. While you’re developing it, you usually don’t want to have a full-blown webserver like Apache up and running, but instead a simple standalone one. With Python 2.5 and onwards, there is the wsgiref server in the standard library. If you’re using older versions of Python you can download the package from the Cheeseshop.

However, there are some caveats. Sourcecode won’t reload itself when changed, and each time you kill the server using ^C you get a KeyboardInterrupt error. While the latter is easy to solve, the first one can be a pain in the ass in some situations.

Because of that Werkzeug ships a small wrapper over wsgiref that spawns the WSGI application in a subprocess and automatically reloads the application if a module was changed.

The easiest way is creating a small start-myproject.py file that runs the application:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from werkzeug import run_simple
from myproject import make_app

app = make_app(...)
run_simple('localhost', 8080, app, use_reloader=True)

You can also pass it the extra_files keyword argument with a list of additional files (like configuration files) you want to observe.

run_simple (hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None)

Start an application using wsgiref and with an optional reloader. This wraps wsgiref to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support.

Parameters

hostname: The host for the application. eg: 'localhost'

port: The port for the server. eg: 8080

application: the WSGI application to execute

use_reloader: should the server automatically restart the python process if modules were changed?

use_debugger: should the werkzeug debugging system be used?

use_evalex: should the exception evaluation feature be enabled?

extra_files: a list of files the reloader should listen for additionally to the modules. For example configuration files.

reloader_interval: the interval for the reloader in seconds.

threaded: should the process handle each request in a separate thread?

processes: number of processes to spawn.

request_handler: optional parameter that can be used to replace the default wsgiref request handler. Have a look at the werkzeug.serving sourcecode for more details.