globals.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import typing as t
  2. from functools import partial
  3. from werkzeug.local import LocalProxy
  4. from werkzeug.local import LocalStack
  5. if t.TYPE_CHECKING:
  6. from .app import Flask
  7. from .ctx import _AppCtxGlobals
  8. from .sessions import SessionMixin
  9. from .wrappers import Request
  10. _request_ctx_err_msg = """\
  11. Working outside of request context.
  12. This typically means that you attempted to use functionality that needed
  13. an active HTTP request. Consult the documentation on testing for
  14. information about how to avoid this problem.\
  15. """
  16. _app_ctx_err_msg = """\
  17. Working outside of application context.
  18. This typically means that you attempted to use functionality that needed
  19. to interface with the current application object in some way. To solve
  20. this, set up an application context with app.app_context(). See the
  21. documentation for more information.\
  22. """
  23. def _lookup_req_object(name):
  24. top = _request_ctx_stack.top
  25. if top is None:
  26. raise RuntimeError(_request_ctx_err_msg)
  27. return getattr(top, name)
  28. def _lookup_app_object(name):
  29. top = _app_ctx_stack.top
  30. if top is None:
  31. raise RuntimeError(_app_ctx_err_msg)
  32. return getattr(top, name)
  33. def _find_app():
  34. top = _app_ctx_stack.top
  35. if top is None:
  36. raise RuntimeError(_app_ctx_err_msg)
  37. return top.app
  38. # context locals
  39. _request_ctx_stack = LocalStack()
  40. _app_ctx_stack = LocalStack()
  41. current_app: "Flask" = LocalProxy(_find_app) # type: ignore
  42. request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore
  43. session: "SessionMixin" = LocalProxy( # type: ignore
  44. partial(_lookup_req_object, "session")
  45. )
  46. g: "_AppCtxGlobals" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore