Skip to content
Myr

appdispatch.rst

This file

Path

docs/patterns/appdispatch.rst

188 lines · 6.8 KiB

Last changed by

Not known.

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 combine not only Flask8applications but any WSGI application.  This would allow you to run a9Django and a Flask application in the same interpreter side by side if10you want.  The usefulness of this depends on how the applications work11internally.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.171819Working with this Document20--------------------------2122Each of the techniques and examples below results in an ``application`` object23that can be run with any WSGI server.  For production, see :ref:`deployment`.24For development, Werkzeug provides a builtin server for development available25at :func:`werkzeug.serving.run_simple`::2627    from werkzeug.serving import run_simple28    run_simple('localhost', 5000, application, use_reloader=True)2930Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for31use in production.  Use a :ref:`full-blown WSGI server <deployment>`.3233In order to use the interactive debugger, debugging must be enabled both on34the application and the simple server. Here is the "hello world" example with35debugging and :func:`run_simple <werkzeug.serving.run_simple>`::3637    from flask import Flask38    from werkzeug.serving import run_simple3940    app = Flask(__name__)41    app.debug = True4243    @app.route('/')44    def hello_world():45        return 'Hello World!'4647    if __name__ == '__main__':48        run_simple('localhost', 5000, app,49                   use_reloader=True, use_debugger=True, use_evalex=True)505152Combining Applications53----------------------5455If you have entirely separated applications and you want them to work next56to each other in the same Python interpreter process you can take57advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`.  The idea58here is that each Flask application is a valid WSGI application and they59are combined by the dispatcher middleware into a larger one that is60dispatched based on prefix.6162For example you could have your main application run on ``/`` and your63backend interface on ``/backend``::6465    from werkzeug.wsgi import DispatcherMiddleware66    from frontend_app import application as frontend67    from backend_app import application as backend6869    application = DispatcherMiddleware(frontend, {70        '/backend':     backend71    })727374Dispatch by Subdomain75---------------------7677Sometimes you might want to use multiple instances of the same application78with different configurations.  Assuming the application is created inside79a function and you can call that function to instantiate it, that is80really easy to implement.  In order to develop your application to support81creating new instances in functions have a look at the82:ref:`app-factories` pattern.8384A very common example would be creating applications per subdomain.  For85instance you configure your webserver to dispatch all requests for all86subdomains to your application and you then use the subdomain information87to create user-specific instances.  Once you have your server set up to88listen on all subdomains you can use a very simple WSGI application to do89the dynamic application creation.9091The perfect level for abstraction in that regard is the WSGI layer.  You92write your own WSGI application that looks at the request that comes and93delegates it to your Flask application.  If that application does not94exist yet, it is dynamically created and remembered::9596    from threading import Lock9798    class SubdomainDispatcher(object):99100        def __init__(self, domain, create_app):101            self.domain = domain102            self.create_app = create_app103            self.lock = Lock()104            self.instances = {}105106        def get_application(self, host):107            host = host.split(':')[0]108            assert host.endswith(self.domain), 'Configuration error'109            subdomain = host[:-len(self.domain)].rstrip('.')110            with self.lock:111                app = self.instances.get(subdomain)112                if app is None:113                    app = self.create_app(subdomain)114                    self.instances[subdomain] = app115                return app116117        def __call__(self, environ, start_response):118            app = self.get_application(environ['HTTP_HOST'])119            return app(environ, start_response)120121122This dispatcher can then be used like this::123124    from myapplication import create_app, get_user_for_subdomain125    from werkzeug.exceptions import NotFound126127    def make_app(subdomain):128        user = get_user_for_subdomain(subdomain)129        if user is None:130            # if there is no user for that subdomain we still have131            # to return a WSGI application that handles that request.132            # We can then just return the NotFound() exception as133            # application which will render a default 404 page.134            # You might also redirect the user to the main page then135            return NotFound()136137        # otherwise create the application for the specific user138        return create_app(user)139140    application = SubdomainDispatcher('example.com', make_app)141142143Dispatch by Path144----------------145146Dispatching by a path on the URL is very similar.  Instead of looking at147the ``Host`` header to figure out the subdomain one simply looks at the148request path up to the first slash::149150    from threading import Lock151    from werkzeug.wsgi import pop_path_info, peek_path_info152153    class PathDispatcher(object):154155        def __init__(self, default_app, create_app):156            self.default_app = default_app157            self.create_app = create_app158            self.lock = Lock()159            self.instances = {}160161        def get_application(self, prefix):162            with self.lock:163                app = self.instances.get(prefix)164                if app is None:165                    app = self.create_app(prefix)166                    if app is not None:167                        self.instances[prefix] = app168                return app169170        def __call__(self, environ, start_response):171            app = self.get_application(peek_path_info(environ))172            if app is not None:173                pop_path_info(environ)174            else:175                app = self.default_app176            return app(environ, start_response)177178The big difference between this and the subdomain one is that this one179falls back to another application if the creator function returns ``None``::180181    from myapplication import create_app, default_app, get_user_for_prefix182183    def make_app(prefix):184        user = get_user_for_prefix(prefix)185        if user is not None:186            return create_app(user)187188    application = PathDispatcher(default_app, make_app)