Navigation

Application dispatching is the process of combining multiple Flask
applications on the WSGI level. You can combine not only Flask
applications but any WSGI application. This would allow you to run a
Django and a Flask application in the same interpreter side by side if
you want. The usefulness of this depends on how the applications work
internally.

The fundamental difference from the module approach is that in this case you are running the same or
different Flask applications that are entirely isolated from each other.
They run different configurations and are dispatched on the WSGI level.

Each of the techniques and examples below results in an application object
that can be run with any WSGI server. For production, see Deployment Options.
For development, Werkzeug provides a builtin server for development available
at werkzeug.serving.run_simple():

If you have entirely separated applications and you want them to work next
to each other in the same Python interpreter process you can take
advantage of the werkzeug.wsgi.DispatcherMiddleware. The idea
here is that each Flask application is a valid WSGI application and they
are combined by the dispatcher middleware into a larger one that is
dispatched based on prefix.

For example you could have your main application run on / and your
backend interface on /backend:

Sometimes you might want to use multiple instances of the same application
with different configurations. Assuming the application is created inside
a function and you can call that function to instantiate it, that is
really easy to implement. In order to develop your application to support
creating new instances in functions have a look at the
Application Factories pattern.

A very common example would be creating applications per subdomain. For
instance you configure your webserver to dispatch all requests for all
subdomains to your application and you then use the subdomain information
to create user-specific instances. Once you have your server set up to
listen on all subdomains you can use a very simple WSGI application to do
the dynamic application creation.

The perfect level for abstraction in that regard is the WSGI layer. You
write your own WSGI application that looks at the request that comes and
delegates it to your Flask application. If that application does not
exist yet, it is dynamically created and remembered:

frommyapplicationimportcreate_app,get_user_for_subdomainfromwerkzeug.exceptionsimportNotFounddefmake_app(subdomain):user=get_user_for_subdomain(subdomain)ifuserisNone:# if there is no user for that subdomain we still have# to return a WSGI application that handles that request.# We can then just return the NotFound() exception as# application which will render a default 404 page.# You might also redirect the user to the main page thenreturnNotFound()# otherwise create the application for the specific userreturncreate_app(user)application=SubdomainDispatcher('example.com',make_app)