Skip to content
Myr

appdispatch.rst

This file

Path

docs/patterns/appdispatch.rst

186 lines · 6.8 KiB

Last changed by

Merge branch '2.2.x'David Lordbefore adoption7464e17

History of this file

Take it

1Application Dispatching2=======================34Application dispatching is the process of combining multiple Flask5applications on the WSGI level.  You can combine not only Flask6applications but any WSGI application.  This would allow you to run a7Django and a Flask application in the same interpreter side by side if8you want.  The usefulness of this depends on how the applications work9internally.1011The fundamental difference from :doc:`packages` is that in this case you12are running the same or different Flask applications that are entirely13isolated from each other. They run different configurations and are14dispatched on the WSGI level.151617Working with this Document18--------------------------1920Each of the techniques and examples below results in an ``application``21object that can be run with any WSGI server. For production, see22:doc:`/deploying/index`. For development, Werkzeug provides a server23through :func:`werkzeug.serving.run_simple`::2425    from werkzeug.serving import run_simple26    run_simple('localhost', 5000, application, use_reloader=True)2728Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for29use in production.  Use a production WSGI server. See :doc:`/deploying/index`.3031In order to use the interactive debugger, debugging must be enabled both on32the application and the simple server. Here is the "hello world" example with33debugging and :func:`run_simple <werkzeug.serving.run_simple>`::3435    from flask import Flask36    from werkzeug.serving import run_simple3738    app = Flask(__name__)39    app.debug = True4041    @app.route('/')42    def hello_world():43        return 'Hello World!'4445    if __name__ == '__main__':46        run_simple('localhost', 5000, app,47                   use_reloader=True, use_debugger=True, use_evalex=True)484950Combining Applications51----------------------5253If you have entirely separated applications and you want them to work next54to each other in the same Python interpreter process you can take55advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`.  The idea56here is that each Flask application is a valid WSGI application and they57are combined by the dispatcher middleware into a larger one that is58dispatched based on prefix.5960For example you could have your main application run on ``/`` and your61backend interface on ``/backend``::6263    from werkzeug.middleware.dispatcher import DispatcherMiddleware64    from frontend_app import application as frontend65    from backend_app import application as backend6667    application = DispatcherMiddleware(frontend, {68        '/backend': backend69    })707172Dispatch by Subdomain73---------------------7475Sometimes you might want to use multiple instances of the same application76with different configurations.  Assuming the application is created inside77a function and you can call that function to instantiate it, that is78really easy to implement.  In order to develop your application to support79creating new instances in functions have a look at the80:doc:`appfactories` pattern.8182A very common example would be creating applications per subdomain.  For83instance you configure your webserver to dispatch all requests for all84subdomains to your application and you then use the subdomain information85to create user-specific instances.  Once you have your server set up to86listen on all subdomains you can use a very simple WSGI application to do87the dynamic application creation.8889The perfect level for abstraction in that regard is the WSGI layer.  You90write your own WSGI application that looks at the request that comes and91delegates it to your Flask application.  If that application does not92exist yet, it is dynamically created and remembered::9394    from threading import Lock9596    class SubdomainDispatcher:9798        def __init__(self, domain, create_app):99            self.domain = domain100            self.create_app = create_app101            self.lock = Lock()102            self.instances = {}103104        def get_application(self, host):105            host = host.split(':')[0]106            assert host.endswith(self.domain), 'Configuration error'107            subdomain = host[:-len(self.domain)].rstrip('.')108            with self.lock:109                app = self.instances.get(subdomain)110                if app is None:111                    app = self.create_app(subdomain)112                    self.instances[subdomain] = app113                return app114115        def __call__(self, environ, start_response):116            app = self.get_application(environ['HTTP_HOST'])117            return app(environ, start_response)118119120This dispatcher can then be used like this::121122    from myapplication import create_app, get_user_for_subdomain123    from werkzeug.exceptions import NotFound124125    def make_app(subdomain):126        user = get_user_for_subdomain(subdomain)127        if user is None:128            # if there is no user for that subdomain we still have129            # to return a WSGI application that handles that request.130            # We can then just return the NotFound() exception as131            # application which will render a default 404 page.132            # You might also redirect the user to the main page then133            return NotFound()134135        # otherwise create the application for the specific user136        return create_app(user)137138    application = SubdomainDispatcher('example.com', make_app)139140141Dispatch by Path142----------------143144Dispatching by a path on the URL is very similar.  Instead of looking at145the ``Host`` header to figure out the subdomain one simply looks at the146request path up to the first slash::147148    from threading import Lock149    from werkzeug.wsgi import pop_path_info, peek_path_info150151    class PathDispatcher:152153        def __init__(self, default_app, create_app):154            self.default_app = default_app155            self.create_app = create_app156            self.lock = Lock()157            self.instances = {}158159        def get_application(self, prefix):160            with self.lock:161                app = self.instances.get(prefix)162                if app is None:163                    app = self.create_app(prefix)164                    if app is not None:165                        self.instances[prefix] = app166                return app167168        def __call__(self, environ, start_response):169            app = self.get_application(peek_path_info(environ))170            if app is not None:171                pop_path_info(environ)172            else:173                app = self.default_app174            return app(environ, start_response)175176The big difference between this and the subdomain one is that this one177falls back to another application if the creator function returns ``None``::178179    from myapplication import create_app, default_app, get_user_for_prefix180181    def make_app(prefix):182        user = get_user_for_prefix(prefix)183        if user is not None:184            return create_app(user)185186    application = PathDispatcher(default_app, make_app)