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
The walk stopped after 200 commits: lines older than 73739a2 point at it.
Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 1–20why, one step back1Application 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``Merge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 21–23why, one step back21object 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`.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 24why, one step back24Merge branch '2.3.x'David Lordbefore adoption9e9acfb
line 25why, one step back25.. code-block:: pythonMerge branch '2.2.x'David Lordbefore adoption73739a2
lines 26–46why, one step back2627 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 yourMerge branch '2.3.x'David Lordbefore adoption9e9acfb
line 47why, one step back47backend interface on ``/backend``.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 48why, one step back48Merge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 49–50why, one step back49.. code-block:: python50Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 51–79why, one step back51 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 notMerge branch '2.3.x'David Lordbefore adoption9e9acfb
line 80why, one step back80exist yet, it is dynamically created and remembered.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 81why, one step back81Merge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 82–83why, one step back82.. code-block:: python83Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 84–109why, one step back84 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)108109Merge branch '2.3.x'David Lordbefore adoption9e9acfb
line 110why, one step back110This dispatcher can then be used like this:Merge branch '2.2.x'David Lordbefore adoption73739a2
line 111why, one step back111Merge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 112–113why, one step back112.. code-block:: python113Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 114–137why, one step back114 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 theMerge branch '2.3.x'David Lordbefore adoption9e9acfb
line 138why, one step back138request path up to the first slash.Merge branch '2.2.x'David Lordbefore adoption73739a2
line 139why, one step back139Merge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 140–141why, one step back140.. code-block:: python141Merge branch '2.2.x'David Lordbefore adoption73739a2
line 142why, one step back142 from threading import LockMerge branch '2.3.x'David Lordbefore adoption9e9acfb
line 143why, one step back143 from wsgiref.util import shift_path_infoMerge branch '2.2.x'David Lordbefore adoption73739a2
lines 144–162why, one step back144145 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):Merge branch '2.3.x'David Lordbefore adoption9e9acfb
line 163why, one step back163 app = self.get_application(_peek_path_info(environ))Merge branch '2.2.x'David Lordbefore adoption73739a2
line 164why, one step back164 if app is not None:Merge branch '2.3.x'David Lordbefore adoption9e9acfb
line 165why, one step back165 shift_path_info(environ)Merge branch '2.2.x'David Lordbefore adoption73739a2
lines 166–169why, one step back166 else:167 app = self.default_app168 return app(environ, start_response)169Merge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 170–176why, one step back170 def _peek_path_info(environ):171 segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)172 if segments:173 return segments[0]174175 return None176Merge branch '2.2.x'David Lordbefore adoption73739a2
line 177why, one step back177The big difference between this and the subdomain one is that this oneMerge branch '2.3.x'David Lordbefore adoption9e9acfb
lines 178–180why, one step back178falls back to another application if the creator function returns ``None``.179180.. code-block:: pythonMerge branch '2.2.x'David Lordbefore adoption73739a2
lines 181–189why, one step back181182 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)