Skip to content
Myr

appdispatch.rst

This file

Path

docs/patterns/appdispatch.rst

170 lines · 6.3 KiB

Last changed by

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption805276a

History of this file

Take it

The walk stopped after 200 commits: lines older than b64fa73 point at it.

HEAD is 0.8-devArmin Ronacherbefore adoptionb64fa73

lines 1–44why, one step back
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.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>`.323334Combining Applications35----------------------3637If you have entirely separated applications and you want them to work next38to each other in the same Python interpreter process you can take39advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea40here is that each Flask application is a valid WSGI application and they41are combined by the dispatcher middleware into a larger one that42dispatched based on prefix.4344For example you could have your main application run on `/` and your

Admin -> BackendArmin Ronacherbefore adoptionc26a6dd

line 45why, one step back
45backend interface on `/backend`::

HEAD is 0.8-devArmin Ronacherbefore adoptionb64fa73

lines 46–169why, one step back
46
47 from werkzeug.wsgi import DispatcherMiddleware48 from frontend_app import application as frontend49 from backend_app import application as backend5051 application = DispatcherMiddleware(frontend, {52 '/backend': backend53 })545556Dispatch by Subdomain57---------------------5859Sometimes you might want to use multiple instances of the same application60with different configurations. Assuming the application is created inside61a function and you can call that function to instanciate it, that is62really easy to implement. In order to develop your application to support63creating new instances in functions have a look at the64:ref:`app-factories` pattern.6566A very common example would be creating applications per subdomain. For67instance you configure your webserver to dispatch all requests for all68subdomains to your application and you then use the subdomain information69to create user-specific instances. Once you have your server set up to70listen on all subdomains you can use a very simple WSGI application to do71the dynamic application creation.7273The perfect level for abstraction in that regard is the WSGI layer. You74write your own WSGI application that looks at the request that comes and75and delegates it to your Flask application. If that application does not76exist yet, it is dynamically created and remembered::7778 from threading import Lock7980 class SubdomainDispatcher(object):8182 def __init__(self, domain, create_app):83 self.domain = domain84 self.create_app = create_app85 self.lock = Lock()86 self.instances = {}8788 def get_application(self, host):89 host = host.split(':')[0]90 assert host.endswith(self.domain), 'Configuration error'91 subdomain = host[:-len(self.domain)].rstrip('.')92 with self.lock:93 app = self.instances.get(subdomain)94 if app is None:95 app = self.create_app(subdomain)96 self.instances[subdomain] = app97 return app9899 def __call__(self, environ, start_response):100 app = self.get_application(environ['HTTP_HOST'])101 return app(environ, start_response)102103104This dispatcher can then be used like this::105106 from myapplication import create_app, get_user_for_subdomain107 from werkzeug.exceptions import NotFound108109 def make_app(subdomain):110 user = get_user_for_subdomain(subdomain)111 if user is None:112 # if there is no user for that subdomain we still have113 # to return a WSGI application that handles that request.114 # We can then just return the NotFound() exception as115 # application which will render a default 404 page.116 # You might also redirect the user to the main page then117 return NotFound()118119 # otherwise create the application for the specific user120 return create_app(user)121122 application = SubdomainDispatcher('example.com', make_app)123124125Dispatch by Path126----------------127128Dispatching by a path on the URL is very similar. Instead of looking at129the `Host` header to figure out the subdomain one simply looks at the130request path up to the first slash::131132 from threading import Lock133 from werkzeug.wsgi import pop_path_info, peek_path_info134135 class PathDispatcher(object):136137 def __init__(self, default_app, create_app):138 self.default_app = default_app139 self.create_app = create_app140 self.lock = Lock()141 self.instances = {}142143 def get_application(self, prefix):144 with self.lock:145 app = self.instances.get(prefix)146 if app is None:147 app = self.create_app(prefix)148 if app is not None:149 self.instances[prefix] = app150 return app151152 def __call__(self, environ, start_response):153 app = self.get_application(peek_path_info(environ))154 if app is not None:155 pop_path_info(environ)156 else:157 app = self.default_app158 return app(environ, start_response)159160The big difference between this and the subdomain one is that this one161falls back to another application if the creator function returns `None`::162163 from myapplication import create_app, default_app, get_user_for_prefix164165 def make_app(prefix):166 user = get_user_for_prefix(prefix)167 if user is not None:168 return create_app(user)169

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption805276a

line 170why, one step back
170 application = PathDispatcher(default_app, make_app)