1
0

globals.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 Pallets
  8. :license: BSD-3-Clause
  9. """
  10. from functools import partial
  11. from werkzeug.local import LocalProxy
  12. from werkzeug.local import LocalStack
  13. _request_ctx_err_msg = """\
  14. Working outside of request context.
  15. This typically means that you attempted to use functionality that needed
  16. an active HTTP request. Consult the documentation on testing for
  17. information about how to avoid this problem.\
  18. """
  19. _app_ctx_err_msg = """\
  20. Working outside of application context.
  21. This typically means that you attempted to use functionality that needed
  22. to interface with the current application object in some way. To solve
  23. this, set up an application context with app.app_context(). See the
  24. documentation for more information.\
  25. """
  26. def _lookup_req_object(name):
  27. top = _request_ctx_stack.top
  28. if top is None:
  29. raise RuntimeError(_request_ctx_err_msg)
  30. return getattr(top, name)
  31. def _lookup_app_object(name):
  32. top = _app_ctx_stack.top
  33. if top is None:
  34. raise RuntimeError(_app_ctx_err_msg)
  35. return getattr(top, name)
  36. def _find_app():
  37. top = _app_ctx_stack.top
  38. if top is None:
  39. raise RuntimeError(_app_ctx_err_msg)
  40. return top.app
  41. # context locals
  42. _request_ctx_stack = LocalStack()
  43. _app_ctx_stack = LocalStack()
  44. current_app = LocalProxy(_find_app)
  45. request = LocalProxy(partial(_lookup_req_object, "request"))
  46. session = LocalProxy(partial(_lookup_req_object, "session"))
  47. g = LocalProxy(partial(_lookup_app_object, "g"))