/kai/config/middleware.py

https://bitbucket.org/bbangert/kai/ · Python · 73 lines · 40 code · 12 blank · 21 comment · 4 complexity · 458d4f31aa81e6c47d9e0985973f743b MD5 · raw file

  1. """Pylons middleware initialization"""
  2. import time
  3. import _strptime
  4. from beaker.middleware import CacheMiddleware, SessionMiddleware
  5. from paste.cascade import Cascade
  6. from paste.registry import RegistryManager
  7. from paste.urlparser import StaticURLParser
  8. from paste.deploy.converters import asbool
  9. from pylons.middleware import ErrorHandler, StatusCodeRedirect
  10. from pylons.wsgiapp import PylonsApp
  11. from routes.middleware import RoutesMiddleware
  12. from tw2.core.middleware import TwMiddleware
  13. from kai.config.environment import load_environment
  14. # Import the docutil extension promptly to ensure the code-block is regged
  15. import kai.lib.pygmentsupport
  16. def make_app(global_conf, full_stack=True, **app_conf):
  17. """Create a Pylons WSGI application and return it
  18. ``global_conf``
  19. The inherited configuration for this application. Normally from
  20. the [DEFAULT] section of the Paste ini file.
  21. ``full_stack``
  22. Whether or not this application provides a full WSGI stack (by
  23. default, meaning it handles its own exceptions and errors).
  24. Disable full_stack when this application is "managed" by
  25. another WSGI middleware.
  26. ``app_conf``
  27. The application's local configuration. Normally specified in
  28. the [app:<name>] section of the Paste ini file (where <name>
  29. defaults to main).
  30. """
  31. # Configure the Pylons environment
  32. config = load_environment(global_conf, app_conf)
  33. # The Pylons WSGI app
  34. app = PylonsApp(config=config)
  35. # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
  36. app = TwMiddleware(app, default_engine='mako')
  37. # Routing/Session/Cache Middleware
  38. app = RoutesMiddleware(app, config['routes.map'])
  39. app = SessionMiddleware(app, config)
  40. if asbool(full_stack):
  41. # Handle Python exceptions
  42. app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
  43. # Display error documents for 401, 403, 404 status codes (and
  44. # 500 when debug is disabled)
  45. if asbool(config['debug']):
  46. app = StatusCodeRedirect(app)
  47. else:
  48. app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])
  49. # Establish the Registry for this application
  50. app = RegistryManager(app)
  51. # Static files (If running in production, and Apache or another web
  52. # server is handling this static content, remove the following 3 lines)
  53. if asbool(config['debug']):
  54. static_app = StaticURLParser(config['pylons.paths']['static_files'])
  55. app = Cascade([static_app, app])
  56. app.config = config
  57. return app