Application Dispatching

    The fundamental difference from the module approach is that in this case you are running the same ordifferent Flask applications that are entirely isolated from each other.They run different configurations and are dispatched on the WSGI level.

    Each of the techniques and examples below results in an objectthat can be run with any WSGI server. For production, see .For development, Werkzeug provides a builtin server for development availableat werkzeug.serving.run_simple():

    Note that is not intended foruse in production. Use a full-blown WSGI server.

    1. from flask import Flask
    2. from werkzeug.serving import run_simple
    3.  
    4. app = Flask(__name__)
    5. app.debug = True
    6.  
    7. @app.route('/')
    8. def hello_world():
    9. return 'Hello World!'
    10.  
    11. if __name__ == '__main__':
    12. run_simple('localhost', 5000, app,
    13. use_reloader=True, use_debugger=True, use_evalex=True)

    If you have entirely separated applications and you want them to work nextto each other in the same Python interpreter process you can takeadvantage of the werkzeug.wsgi.DispatcherMiddleware. The ideahere is that each Flask application is a valid WSGI application and theyare combined by the dispatcher middleware into a larger one that isdispatched based on prefix.

    For example you could have your main application run on / and yourbackend interface on :

    Sometimes you might want to use multiple instances of the same applicationwith different configurations. Assuming the application is created insidea function and you can call that function to instantiate it, that isreally easy to implement. In order to develop your application to supportcreating new instances in functions have a look at the pattern.

    The perfect level for abstraction in that regard is the WSGI layer. Youwrite your own WSGI application that looks at the request that comes anddelegates it to your Flask application. If that application does notexist yet, it is dynamically created and remembered:

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

    This dispatcher can then be used like this:

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

    1. from threading import Lock
    2. from werkzeug.wsgi import pop_path_info, peek_path_info
    3.  
    4. class PathDispatcher(object):
    5. def __init__(self, default_app, create_app):
    6. self.default_app = default_app
    7. self.create_app = create_app
    8. self.lock = Lock()
    9. self.instances = {}
    10.  
    11. def get_application(self, prefix):
    12. with self.lock:
    13. app = self.instances.get(prefix)
    14. if app is None:
    15. app = self.create_app(prefix)
    16. if app is not None:
    17. self.instances[prefix] = app
    18. return app
    19.  
    20. def __call__(self, environ, start_response):
    21. app = self.get_application(peek_path_info(environ))
    22. if app is not None:
    23. pop_path_info(environ)
    24. else:
    25. app = self.default_app
    26. return app(environ, start_response)