appdispatch.rst
This file
Path
docs/patterns/appdispatch.rst
189 lines · 6.4 KiB
Last changed by
Merge branch '2.3.x'David Lordbefore adoption9e9acfb
History of this fileTake 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 development, use the22``flask run`` command to start a development server. For production, see23:doc:`/deploying/index`.2425.. code-block:: python2627 from flask import Flask2829 app = Flask(__name__)3031 @app.route('/')32 def hello_world():33 return 'Hello World!'343536Combining Applications37----------------------3839If you have entirely separated applications and you want them to work next40to each other in the same Python interpreter process you can take41advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea42here is that each Flask application is a valid WSGI application and they43are combined by the dispatcher middleware into a larger one that is44dispatched based on prefix.4546For example you could have your main application run on ``/`` and your47backend interface on ``/backend``.4849.. code-block:: python5051 from werkzeug.middleware.dispatcher import DispatcherMiddleware52 from frontend_app import application as frontend53 from backend_app import application as backend5455 application = DispatcherMiddleware(frontend, {56 '/backend': backend57 })585960Dispatch by Subdomain61---------------------6263Sometimes you might want to use multiple instances of the same application64with different configurations. Assuming the application is created inside65a function and you can call that function to instantiate it, that is66really easy to implement. In order to develop your application to support67creating new instances in functions have a look at the68:doc:`appfactories` pattern.6970A very common example would be creating applications per subdomain. For71instance you configure your webserver to dispatch all requests for all72subdomains to your application and you then use the subdomain information73to create user-specific instances. Once you have your server set up to74listen on all subdomains you can use a very simple WSGI application to do75the dynamic application creation.7677The perfect level for abstraction in that regard is the WSGI layer. You78write your own WSGI application that looks at the request that comes and79delegates it to your Flask application. If that application does not80exist yet, it is dynamically created and remembered.8182.. code-block:: python8384 from threading import Lock8586 class SubdomainDispatcher:8788 def __init__(self, domain, create_app):89 self.domain = domain90 self.create_app = create_app91 self.lock = Lock()92 self.instances = {}9394 def get_application(self, host):95 host = host.split(':')[0]96 assert host.endswith(self.domain), 'Configuration error'97 subdomain = host[:-len(self.domain)].rstrip('.')98 with self.lock:99 app = self.instances.get(subdomain)100 if app is None:101 app = self.create_app(subdomain)102 self.instances[subdomain] = app103 return app104105 def __call__(self, environ, start_response):106 app = self.get_application(environ['HTTP_HOST'])107 return app(environ, start_response)108109110This dispatcher can then be used like this:111112.. code-block:: python113114 from myapplication import create_app, get_user_for_subdomain115 from werkzeug.exceptions import NotFound116117 def make_app(subdomain):118 user = get_user_for_subdomain(subdomain)119 if user is None:120 # if there is no user for that subdomain we still have121 # to return a WSGI application that handles that request.122 # We can then just return the NotFound() exception as123 # application which will render a default 404 page.124 # You might also redirect the user to the main page then125 return NotFound()126127 # otherwise create the application for the specific user128 return create_app(user)129130 application = SubdomainDispatcher('example.com', make_app)131132133Dispatch by Path134----------------135136Dispatching by a path on the URL is very similar. Instead of looking at137the ``Host`` header to figure out the subdomain one simply looks at the138request path up to the first slash.139140.. code-block:: python141142 from threading import Lock143 from wsgiref.util import shift_path_info144145 class PathDispatcher:146147 def __init__(self, default_app, create_app):148 self.default_app = default_app149 self.create_app = create_app150 self.lock = Lock()151 self.instances = {}152153 def get_application(self, prefix):154 with self.lock:155 app = self.instances.get(prefix)156 if app is None:157 app = self.create_app(prefix)158 if app is not None:159 self.instances[prefix] = app160 return app161162 def __call__(self, environ, start_response):163 app = self.get_application(_peek_path_info(environ))164 if app is not None:165 shift_path_info(environ)166 else:167 app = self.default_app168 return app(environ, start_response)169170 def _peek_path_info(environ):171 segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)172 if segments:173 return segments[0]174175 return None176177The big difference between this and the subdomain one is that this one178falls back to another application if the creator function returns ``None``.179180.. code-block:: python181182 from myapplication import create_app, default_app, get_user_for_prefix183184 def make_app(prefix):185 user = get_user_for_prefix(prefix)186 if user is not None:187 return create_app(user)188189 application = PathDispatcher(default_app, make_app)