Skip to content
Myr

appdispatch.rst

This file

Path

docs/patterns/appdispatch.rst

154 lines · 5.7 KiB

Last changed by

Merge branch 'appdispatch-docs'Armin Ronacherbefore adoptiondd75cc9

History of this file

Take it

1.. _app-dispatch:23Application Dispatching4=======================56Application dispatching is the process of combining multiple Flask7applications on the WSGI level.  You can not only combine Flask8applications into something larger but any WSGI application.  This would9even allow you to run a Django and a Flask application in the same10interpreter side by side if you want.  The usefulness of this depends on11how the applications work internally.1213The fundamental difference from the :ref:`module approach14<larger-applications>` is that in this case you are running the same or15different Flask applications that are entirely isolated from each other.16They run different configurations and are dispatched on the WSGI level.1718Combining Applications19----------------------2021If you have entirely separated applications and you want them to work next22to each other in the same Python interpreter process you can take23advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`.  The idea24here is that each Flask application is a valid WSGI application and they25are combined by the dispatcher middleware into a larger one that26dispatched based on prefix.2728For example you could have your main application run on `/` and your29backend interface on `/admin`::3031    from werkzeug.wsgi import DispatcherMiddleware32    from frontend_app import application as frontend33    from backend_app import application as backend3435    application = DispatcherMiddleware(frontend, {36        '/backend':     backend37    })383940Dispatch by Subdomain41---------------------4243Sometimes you might want to use multiple instances of the same application44with different configurations.  Assuming the application is created inside45a function and you can call that function to instanciate it, that is46really easy to implement.  In order to develop your application to support47creating new instances in functions have a look at the48:ref:`app-factories` pattern.4950A very common example would be creating applications per subdomain.  For51instance you configure your webserver to dispatch all requests for all52subdomains to your application and you then use the subdomain information53to create user-specific instances.  Once you have your server set up to54listen on all subdomains you can use a very simple WSGI application to do55the dynamic application creation.5657The perfect level for abstraction in that regard is the WSGI layer.  You58write your own WSGI application that looks at the request that comes and59and delegates it to your Flask application.  If that application does not60exist yet, it is dynamically created and remembered::6162    from threading import Lock6364    class SubdomainDispatcher(object):6566        def __init__(self, domain, create_app):67            self.domain = domain68            self.create_app = create_app69            self.lock = Lock()70            self.instances = {}7172        def get_application(self, host):73            host = host.split(':')[0]74            assert host.endswith(self.domain), 'Configuration error'75            subdomain = host[:-len(self.domain)].rstrip('.')76            with self.lock:77                app = self.instances.get(subdomain)78                if app is None:79                    app = self.create_app(subdomain)80                    self.instances[subdomain] = app81                return app8283        def __call__(self, environ, start_response):84            app = self.get_application(environ['HTTP_HOST'])85            return app(environ, start_response)868788This dispatcher can then be used like this::8990    from myapplication import create_app, get_user_for_subdomain91    from werkzeug.exceptions import NotFound9293    def make_app(subdomain):94        user = get_user_for_subdomain(subdomain)95        if user is None:96            # if there is no user for that subdomain we still have97            # to return a WSGI application that handles that request.98            # We can then just return the NotFound() exception as99            # application which will render a default 404 page.100            # You might also redirect the user to the main page then101            return NotFound()102103        # otherwise create the application for the specific user104        return create_app(user)105106    application = SubdomainDispatcher('example.com', make_app)107108109Dispatch by Path110----------------111112Dispatching by a path on the URL is very similar.  Instead of looking at113the `Host` header to figure out the subdomain one simply looks at the114request path up to the first slash::115116    from threading import Lock117    from werkzeug.wsgi import pop_path_info, peek_path_info118119    class PathDispatcher(object):120121        def __init__(self, default_app, create_app):122            self.default_app = default_app123            self.create_app = create_app124            self.lock = Lock()125            self.instances = {}126127        def get_application(self, prefix):128            with self.lock:129                app = self.instances.get(prefix)130                if app is None:131                    app = self.create_app(prefix)132                    if app is not None:133                        self.instances[prefix] = app134                return app135136        def __call__(self, environ, start_response):137            app = self.get_application(peek_path_info(environ))138            if app is not None:139                pop_path_info(environ)140            else:141                app = self.default_app142            return app(environ, start_response)143144The big difference between this and the subdomain one is that this one145falls back to another application if the creator function returns `None`::146147    from myapplication import create_app, default_app, get_user_for_prefix148149    def make_app(prefix):150        user = get_user_for_prefix(prefix)151        if user is not None:152            return create_app(user)153154    application = PathDispatcher('example.com', default_app, make_app)