globals.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.globals
  4. ~~~~~~~~~~~~~
  5. Defines all the global objects that are proxies to the current
  6. active context.
  7. :copyright: © 2010 by the Pallets team.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. from functools import partial
  11. from werkzeug.local import LocalStack, LocalProxy
  12. _request_ctx_err_msg = '''\
  13. Working outside of request context.
  14. This typically means that you attempted to use functionality that needed
  15. an active HTTP request. Consult the documentation on testing for
  16. information about how to avoid this problem.\
  17. '''
  18. _app_ctx_err_msg = '''\
  19. Working outside of application context.
  20. This typically means that you attempted to use functionality that needed
  21. to interface with the current application object in some way. To solve
  22. this, set up an application context with app.app_context(). See the
  23. documentation for more information.\
  24. '''
  25. def _lookup_req_object(name):
  26. top = _request_ctx_stack.top
  27. if top is None:
  28. raise RuntimeError(_request_ctx_err_msg)
  29. return getattr(top, name)
  30. def _lookup_app_object(name):
  31. top = _app_ctx_stack.top
  32. if top is None:
  33. raise RuntimeError(_app_ctx_err_msg)
  34. return getattr(top, name)
  35. def _find_app():
  36. top = _app_ctx_stack.top
  37. if top is None:
  38. raise RuntimeError(_app_ctx_err_msg)
  39. return top.app
  40. # context locals
  41. _request_ctx_stack = LocalStack()
  42. _app_ctx_stack = LocalStack()
  43. current_app = LocalProxy(_find_app)
  44. request = LocalProxy(partial(_lookup_req_object, 'request'))
  45. session = LocalProxy(partial(_lookup_req_object, 'session'))
  46. g = LocalProxy(partial(_lookup_app_object, 'g'))