appdispatch.rst
This file
Path
docs/patterns/appdispatch.rst
188 lines · 6.8 KiB
Last changed by
Fix typo pointed out by tri on #pocoo.Ron DuPlainbefore adoptionb885edf
History of this fileTake it
The walk stopped after 200 commits: lines older than 0b33693 point at it.
Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693
lines 1–32why, one step back1.. _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>`.32Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb
lines 33–50why, one step back33In order to use the interactive debuggger, 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)50Allow loading template from iterableDmitry Shevchenkobefore adoption0b33693
lines 51–92why, one step back5152Combining 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 that60dispatched 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 andFix typo pointed out by tri on #pocoo.Ron DuPlainbefore adoptionb885edf
line 93why, one step back93delegates it to your Flask application. If that application does notAllow loading template from iterableDmitry Shevchenkobefore adoption0b33693
lines 94–188why, one step back94exist 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)