Application Dispatching

Application dispatching is the process of combining multiple Flask applications on the WSGI level. You can combine not only Flask applications but any WSGI application. This would allow you to run a Django and a Flask application in the same interpreter side by side if you want. The usefulness of this depends on how the applications work internally.

The fundamental difference from Large Applications as Packages is that in this case you are running the same or different Flask applications that are entirely isolated from each other. They run different configurations and are dispatched on the WSGI level.

Working with this Document

Each of the techniques and examples below results in an application object that can be run with any WSGI server. For development, use the flask run command to start a development server. For production, see Deploying to Production.

  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return 'Hello World!'

Combining Applications

If you have entirely separated applications and you want them to work next to each other in the same Python interpreter process you can take advantage of the werkzeug.wsgi.DispatcherMiddleware. The idea here is that each Flask application is a valid WSGI application and they are combined by the dispatcher middleware into a larger one that is dispatched based on prefix.

For example you could have your main application run on / and your backend interface on /backend.

  1. from werkzeug.middleware.dispatcher import DispatcherMiddleware
  2. from frontend_app import application as frontend
  3. from backend_app import application as backend
  4. application = DispatcherMiddleware(frontend, {
  5. '/backend': backend
  6. })

Dispatch by Subdomain

Sometimes you might want to use multiple instances of the same application with different configurations. Assuming the application is created inside a function and you can call that function to instantiate it, that is really easy to implement. In order to develop your application to support creating new instances in functions have a look at the Application Factories pattern.

A very common example would be creating applications per subdomain. For instance you configure your webserver to dispatch all requests for all subdomains to your application and you then use the subdomain information to create user-specific instances. Once you have your server set up to listen on all subdomains you can use a very simple WSGI application to do the dynamic application creation.

The perfect level for abstraction in that regard is the WSGI layer. You write your own WSGI application that looks at the request that comes and delegates it to your Flask application. If that application does not exist yet, it is dynamically created and remembered.

  1. from threading import Lock
  2. class SubdomainDispatcher:
  3. def __init__(self, domain, create_app):
  4. self.domain = domain
  5. self.create_app = create_app
  6. self.lock = Lock()
  7. self.instances = {}
  8. def get_application(self, host):
  9. host = host.split(':')[0]
  10. assert host.endswith(self.domain), 'Configuration error'
  11. subdomain = host[:-len(self.domain)].rstrip('.')
  12. with self.lock:
  13. app = self.instances.get(subdomain)
  14. if app is None:
  15. app = self.create_app(subdomain)
  16. self.instances[subdomain] = app
  17. return app
  18. def __call__(self, environ, start_response):
  19. app = self.get_application(environ['HTTP_HOST'])
  20. return app(environ, start_response)

This dispatcher can then be used like this:

  1. from myapplication import create_app, get_user_for_subdomain
  2. from werkzeug.exceptions import NotFound
  3. def make_app(subdomain):
  4. user = get_user_for_subdomain(subdomain)
  5. if user is None:
  6. # if there is no user for that subdomain we still have
  7. # to return a WSGI application that handles that request.
  8. # We can then just return the NotFound() exception as
  9. # application which will render a default 404 page.
  10. # You might also redirect the user to the main page then
  11. return NotFound()
  12. # otherwise create the application for the specific user
  13. return create_app(user)
  14. application = SubdomainDispatcher('example.com', make_app)

Dispatch by Path

Dispatching by a path on the URL is very similar. Instead of looking at the Host header to figure out the subdomain one simply looks at the request path up to the first slash.

  1. from threading import Lock
  2. from wsgiref.util import shift_path_info
  3. class PathDispatcher:
  4. def __init__(self, default_app, create_app):
  5. self.default_app = default_app
  6. self.create_app = create_app
  7. self.lock = Lock()
  8. self.instances = {}
  9. def get_application(self, prefix):
  10. with self.lock:
  11. app = self.instances.get(prefix)
  12. if app is None:
  13. app = self.create_app(prefix)
  14. if app is not None:
  15. self.instances[prefix] = app
  16. return app
  17. def __call__(self, environ, start_response):
  18. app = self.get_application(_peek_path_info(environ))
  19. if app is not None:
  20. shift_path_info(environ)
  21. else:
  22. app = self.default_app
  23. return app(environ, start_response)
  24. def _peek_path_info(environ):
  25. segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)
  26. if segments:
  27. return segments[0]
  28. return None

The big difference between this and the subdomain one is that this one falls back to another application if the creator function returns None.

  1. from myapplication import create_app, default_app, get_user_for_prefix
  2. def make_app(prefix):
  3. user = get_user_for_prefix(prefix)
  4. if user is not None:
  5. return create_app(user)
  6. application = PathDispatcher(default_app, make_app)