Werkzeug

wsgi utility collection


Dynamic Dispatching

Sometimes it can be useful to create applications on the first request to that application, based on the WSGI environment. For example you want to host multiple instances of your application using mod_wsgi or something similar and provide the path to the configuration file for a particular application in the WSGI environment (for example as yourapplication.configuration).

The following code implements that:

instances = {}

def application(environ, start_response):
    configuration = environ['yourapplication.configuration']
    if configuration not in instances:
        instances[configuration] = app = YourApplication(configuration)
    else:
        app = instances[configuration]
    return app(environ, start_response)

All you have to do now is to put a yourapplication.configuration variable into the WSGI environment. Using mod_wsgi this could look like this:

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/yourapp/([^/]+)
RewriteCond /var/yourapp/sites/%1/yourapp.ini !-f
RewriteRule . - [F]
RewriteCond %{REQUEST_URI} ^/yourapp/([^/]+)
RewriteRule . - [E=yourapp.configuration:/var/yourapp/sites/%1/yourapp.ini]
WSGIScriptAliasMatch ^/yourapp/([^/]+) /var/yourapp/yourapp.wsgi

This way you can also reload your application if the configuration changes by storing the mtimes of the configurations and checking them each request.