Skip to content
Myr

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 file

Take it

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

fix pr linkDavid Lordbefore adoption979e0ad

lines 1–20why, one step back
1Application Dispatching
2=======================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``

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 21–23why, one step back
21object that can be run with any WSGI server. For development, use the
22``flask run`` command to start a development server. For production, see23:doc:`/deploying/index`.

fix pr linkDavid Lordbefore adoption979e0ad

line 24why, one step back
24

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 25why, one step back
25.. code-block:: python

fix pr linkDavid Lordbefore adoption979e0ad

lines 26–46why, one step back
26
27 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 your

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 47why, one step back
47backend interface on ``/backend``.

fix pr linkDavid Lordbefore adoption979e0ad

line 48why, one step back
48

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 49–50why, one step back
49.. code-block:: python
50

fix pr linkDavid Lordbefore adoption979e0ad

lines 51–79why, one step back
51 from werkzeug.middleware.dispatcher import DispatcherMiddleware
52 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 not

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 80why, one step back
80exist yet, it is dynamically created and remembered.

fix pr linkDavid Lordbefore adoption979e0ad

line 81why, one step back
81

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 82–83why, one step back
82.. code-block:: python
83

fix pr linkDavid Lordbefore adoption979e0ad

lines 84–85why, one step back
84 from threading import Lock
85

Merge branch '2.2.x'David Lordbefore adoption7464e17

line 86why, one step back
86 class SubdomainDispatcher:

fix pr linkDavid Lordbefore adoption979e0ad

lines 87–109why, one step back
87
88 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)108109

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 110why, one step back
110This dispatcher can then be used like this:

fix pr linkDavid Lordbefore adoption979e0ad

line 111why, one step back
111

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 112–113why, one step back
112.. code-block:: python
113

fix pr linkDavid Lordbefore adoption979e0ad

lines 114–137why, one step back
114 from myapplication import create_app, get_user_for_subdomain
115 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 the

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 138why, one step back
138request path up to the first slash.

fix pr linkDavid Lordbefore adoption979e0ad

line 139why, one step back
139

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 140–141why, one step back
140.. code-block:: python
141

fix pr linkDavid Lordbefore adoption979e0ad

line 142why, one step back
142 from threading import Lock

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 143why, one step back
143 from wsgiref.util import shift_path_info

fix pr linkDavid Lordbefore adoption979e0ad

line 144why, one step back
144

Merge branch '2.2.x'David Lordbefore adoption7464e17

line 145why, one step back
145 class PathDispatcher:

fix pr linkDavid Lordbefore adoption979e0ad

lines 146–162why, one step back
146
147 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):

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 163why, one step back
163 app = self.get_application(_peek_path_info(environ))

fix pr linkDavid Lordbefore adoption979e0ad

line 164why, one step back
164 if app is not None:

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

line 165why, one step back
165 shift_path_info(environ)

fix pr linkDavid Lordbefore adoption979e0ad

lines 166–169why, one step back
166 else:
167 app = self.default_app168 return app(environ, start_response)169

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 170–176why, one step back
170 def _peek_path_info(environ):
171 segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)172 if segments:173 return segments[0]174175 return None176

fix pr linkDavid Lordbefore adoption979e0ad

line 177why, one step back
177The big difference between this and the subdomain one is that this one

Merge branch '2.3.x'David Lordbefore adoption9e9acfb

lines 178–180why, one step back
178falls back to another application if the creator function returns ``None``.
179180.. code-block:: python

fix pr linkDavid Lordbefore adoption979e0ad

lines 181–189why, one step back
181
182 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)