1
0

dispatcher.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Application Dispatcher
  3. ======================
  4. This middleware creates a single WSGI application that dispatches to
  5. multiple other WSGI applications mounted at different URL paths.
  6. A common example is writing a Single Page Application, where you have a
  7. backend API and a frontend written in JavaScript that does the routing
  8. in the browser rather than requesting different pages from the server.
  9. The frontend is a single HTML and JS file that should be served for any
  10. path besides "/api".
  11. This example dispatches to an API app under "/api", an admin app
  12. under "/admin", and an app that serves frontend files for all other
  13. requests::
  14. app = DispatcherMiddleware(serve_frontend, {
  15. '/api': api_app,
  16. '/admin': admin_app,
  17. })
  18. In production, you might instead handle this at the HTTP server level,
  19. serving files or proxying to application servers based on location. The
  20. API and admin apps would each be deployed with a separate WSGI server,
  21. and the static files would be served directly by the HTTP server.
  22. .. autoclass:: DispatcherMiddleware
  23. :copyright: 2007 Pallets
  24. :license: BSD-3-Clause
  25. """
  26. class DispatcherMiddleware(object):
  27. """Combine multiple applications as a single WSGI application.
  28. Requests are dispatched to an application based on the path it is
  29. mounted under.
  30. :param app: The WSGI application to dispatch to if the request
  31. doesn't match a mounted path.
  32. :param mounts: Maps path prefixes to applications for dispatching.
  33. """
  34. def __init__(self, app, mounts=None):
  35. self.app = app
  36. self.mounts = mounts or {}
  37. def __call__(self, environ, start_response):
  38. script = environ.get("PATH_INFO", "")
  39. path_info = ""
  40. while "/" in script:
  41. if script in self.mounts:
  42. app = self.mounts[script]
  43. break
  44. script, last_item = script.rsplit("/", 1)
  45. path_info = "/%s%s" % (last_item, path_info)
  46. else:
  47. app = self.mounts.get(script, self.app)
  48. original_script_name = environ.get("SCRIPT_NAME", "")
  49. environ["SCRIPT_NAME"] = original_script_name + script
  50. environ["PATH_INFO"] = path_info
  51. return app(environ, start_response)