ctx.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import sys
  2. import typing as t
  3. from functools import update_wrapper
  4. from types import TracebackType
  5. from werkzeug.exceptions import HTTPException
  6. from . import typing as ft
  7. from .globals import _app_ctx_stack
  8. from .globals import _request_ctx_stack
  9. from .signals import appcontext_popped
  10. from .signals import appcontext_pushed
  11. if t.TYPE_CHECKING:
  12. from .app import Flask
  13. from .sessions import SessionMixin
  14. from .wrappers import Request
  15. # a singleton sentinel value for parameter defaults
  16. _sentinel = object()
  17. class _AppCtxGlobals:
  18. """A plain object. Used as a namespace for storing data during an
  19. application context.
  20. Creating an app context automatically creates this object, which is
  21. made available as the :data:`g` proxy.
  22. .. describe:: 'key' in g
  23. Check whether an attribute is present.
  24. .. versionadded:: 0.10
  25. .. describe:: iter(g)
  26. Return an iterator over the attribute names.
  27. .. versionadded:: 0.10
  28. """
  29. # Define attr methods to let mypy know this is a namespace object
  30. # that has arbitrary attributes.
  31. def __getattr__(self, name: str) -> t.Any:
  32. try:
  33. return self.__dict__[name]
  34. except KeyError:
  35. raise AttributeError(name) from None
  36. def __setattr__(self, name: str, value: t.Any) -> None:
  37. self.__dict__[name] = value
  38. def __delattr__(self, name: str) -> None:
  39. try:
  40. del self.__dict__[name]
  41. except KeyError:
  42. raise AttributeError(name) from None
  43. def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:
  44. """Get an attribute by name, or a default value. Like
  45. :meth:`dict.get`.
  46. :param name: Name of attribute to get.
  47. :param default: Value to return if the attribute is not present.
  48. .. versionadded:: 0.10
  49. """
  50. return self.__dict__.get(name, default)
  51. def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:
  52. """Get and remove an attribute by name. Like :meth:`dict.pop`.
  53. :param name: Name of attribute to pop.
  54. :param default: Value to return if the attribute is not present,
  55. instead of raising a ``KeyError``.
  56. .. versionadded:: 0.11
  57. """
  58. if default is _sentinel:
  59. return self.__dict__.pop(name)
  60. else:
  61. return self.__dict__.pop(name, default)
  62. def setdefault(self, name: str, default: t.Any = None) -> t.Any:
  63. """Get the value of an attribute if it is present, otherwise
  64. set and return a default value. Like :meth:`dict.setdefault`.
  65. :param name: Name of attribute to get.
  66. :param default: Value to set and return if the attribute is not
  67. present.
  68. .. versionadded:: 0.11
  69. """
  70. return self.__dict__.setdefault(name, default)
  71. def __contains__(self, item: str) -> bool:
  72. return item in self.__dict__
  73. def __iter__(self) -> t.Iterator[str]:
  74. return iter(self.__dict__)
  75. def __repr__(self) -> str:
  76. top = _app_ctx_stack.top
  77. if top is not None:
  78. return f"<flask.g of {top.app.name!r}>"
  79. return object.__repr__(self)
  80. def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:
  81. """Executes a function after this request. This is useful to modify
  82. response objects. The function is passed the response object and has
  83. to return the same or a new one.
  84. Example::
  85. @app.route('/')
  86. def index():
  87. @after_this_request
  88. def add_header(response):
  89. response.headers['X-Foo'] = 'Parachute'
  90. return response
  91. return 'Hello World!'
  92. This is more useful if a function other than the view function wants to
  93. modify a response. For instance think of a decorator that wants to add
  94. some headers without converting the return value into a response object.
  95. .. versionadded:: 0.9
  96. """
  97. top = _request_ctx_stack.top
  98. if top is None:
  99. raise RuntimeError(
  100. "This decorator can only be used when a request context is"
  101. " active, such as within a view function."
  102. )
  103. top._after_request_functions.append(f)
  104. return f
  105. def copy_current_request_context(f: t.Callable) -> t.Callable:
  106. """A helper function that decorates a function to retain the current
  107. request context. This is useful when working with greenlets. The moment
  108. the function is decorated a copy of the request context is created and
  109. then pushed when the function is called. The current session is also
  110. included in the copied request context.
  111. Example::
  112. import gevent
  113. from flask import copy_current_request_context
  114. @app.route('/')
  115. def index():
  116. @copy_current_request_context
  117. def do_some_work():
  118. # do some work here, it can access flask.request or
  119. # flask.session like you would otherwise in the view function.
  120. ...
  121. gevent.spawn(do_some_work)
  122. return 'Regular response'
  123. .. versionadded:: 0.10
  124. """
  125. top = _request_ctx_stack.top
  126. if top is None:
  127. raise RuntimeError(
  128. "This decorator can only be used when a request context is"
  129. " active, such as within a view function."
  130. )
  131. reqctx = top.copy()
  132. def wrapper(*args, **kwargs):
  133. with reqctx:
  134. return reqctx.app.ensure_sync(f)(*args, **kwargs)
  135. return update_wrapper(wrapper, f)
  136. def has_request_context() -> bool:
  137. """If you have code that wants to test if a request context is there or
  138. not this function can be used. For instance, you may want to take advantage
  139. of request information if the request object is available, but fail
  140. silently if it is unavailable.
  141. ::
  142. class User(db.Model):
  143. def __init__(self, username, remote_addr=None):
  144. self.username = username
  145. if remote_addr is None and has_request_context():
  146. remote_addr = request.remote_addr
  147. self.remote_addr = remote_addr
  148. Alternatively you can also just test any of the context bound objects
  149. (such as :class:`request` or :class:`g`) for truthness::
  150. class User(db.Model):
  151. def __init__(self, username, remote_addr=None):
  152. self.username = username
  153. if remote_addr is None and request:
  154. remote_addr = request.remote_addr
  155. self.remote_addr = remote_addr
  156. .. versionadded:: 0.7
  157. """
  158. return _request_ctx_stack.top is not None
  159. def has_app_context() -> bool:
  160. """Works like :func:`has_request_context` but for the application
  161. context. You can also just do a boolean check on the
  162. :data:`current_app` object instead.
  163. .. versionadded:: 0.9
  164. """
  165. return _app_ctx_stack.top is not None
  166. class AppContext:
  167. """The application context binds an application object implicitly
  168. to the current thread or greenlet, similar to how the
  169. :class:`RequestContext` binds request information. The application
  170. context is also implicitly created if a request context is created
  171. but the application is not on top of the individual application
  172. context.
  173. """
  174. def __init__(self, app: "Flask") -> None:
  175. self.app = app
  176. self.url_adapter = app.create_url_adapter(None)
  177. self.g = app.app_ctx_globals_class()
  178. # Like request context, app contexts can be pushed multiple times
  179. # but there a basic "refcount" is enough to track them.
  180. self._refcnt = 0
  181. def push(self) -> None:
  182. """Binds the app context to the current context."""
  183. self._refcnt += 1
  184. _app_ctx_stack.push(self)
  185. appcontext_pushed.send(self.app)
  186. def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
  187. """Pops the app context."""
  188. try:
  189. self._refcnt -= 1
  190. if self._refcnt <= 0:
  191. if exc is _sentinel:
  192. exc = sys.exc_info()[1]
  193. self.app.do_teardown_appcontext(exc)
  194. finally:
  195. rv = _app_ctx_stack.pop()
  196. assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"
  197. appcontext_popped.send(self.app)
  198. def __enter__(self) -> "AppContext":
  199. self.push()
  200. return self
  201. def __exit__(
  202. self,
  203. exc_type: t.Optional[type],
  204. exc_value: t.Optional[BaseException],
  205. tb: t.Optional[TracebackType],
  206. ) -> None:
  207. self.pop(exc_value)
  208. class RequestContext:
  209. """The request context contains all request relevant information. It is
  210. created at the beginning of the request and pushed to the
  211. `_request_ctx_stack` and removed at the end of it. It will create the
  212. URL adapter and request object for the WSGI environment provided.
  213. Do not attempt to use this class directly, instead use
  214. :meth:`~flask.Flask.test_request_context` and
  215. :meth:`~flask.Flask.request_context` to create this object.
  216. When the request context is popped, it will evaluate all the
  217. functions registered on the application for teardown execution
  218. (:meth:`~flask.Flask.teardown_request`).
  219. The request context is automatically popped at the end of the request
  220. for you. In debug mode the request context is kept around if
  221. exceptions happen so that interactive debuggers have a chance to
  222. introspect the data. With 0.4 this can also be forced for requests
  223. that did not fail and outside of ``DEBUG`` mode. By setting
  224. ``'flask._preserve_context'`` to ``True`` on the WSGI environment the
  225. context will not pop itself at the end of the request. This is used by
  226. the :meth:`~flask.Flask.test_client` for example to implement the
  227. deferred cleanup functionality.
  228. You might find this helpful for unittests where you need the
  229. information from the context local around for a little longer. Make
  230. sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in
  231. that situation, otherwise your unittests will leak memory.
  232. """
  233. def __init__(
  234. self,
  235. app: "Flask",
  236. environ: dict,
  237. request: t.Optional["Request"] = None,
  238. session: t.Optional["SessionMixin"] = None,
  239. ) -> None:
  240. self.app = app
  241. if request is None:
  242. request = app.request_class(environ)
  243. self.request = request
  244. self.url_adapter = None
  245. try:
  246. self.url_adapter = app.create_url_adapter(self.request)
  247. except HTTPException as e:
  248. self.request.routing_exception = e
  249. self.flashes = None
  250. self.session = session
  251. # Request contexts can be pushed multiple times and interleaved with
  252. # other request contexts. Now only if the last level is popped we
  253. # get rid of them. Additionally if an application context is missing
  254. # one is created implicitly so for each level we add this information
  255. self._implicit_app_ctx_stack: t.List[t.Optional["AppContext"]] = []
  256. # indicator if the context was preserved. Next time another context
  257. # is pushed the preserved context is popped.
  258. self.preserved = False
  259. # remembers the exception for pop if there is one in case the context
  260. # preservation kicks in.
  261. self._preserved_exc = None
  262. # Functions that should be executed after the request on the response
  263. # object. These will be called before the regular "after_request"
  264. # functions.
  265. self._after_request_functions: t.List[ft.AfterRequestCallable] = []
  266. @property
  267. def g(self) -> _AppCtxGlobals:
  268. import warnings
  269. warnings.warn(
  270. "Accessing 'g' on the request context is deprecated and"
  271. " will be removed in Flask 2.2. Access `g` directly or from"
  272. "the application context instead.",
  273. DeprecationWarning,
  274. stacklevel=2,
  275. )
  276. return _app_ctx_stack.top.g
  277. @g.setter
  278. def g(self, value: _AppCtxGlobals) -> None:
  279. import warnings
  280. warnings.warn(
  281. "Setting 'g' on the request context is deprecated and"
  282. " will be removed in Flask 2.2. Set it on the application"
  283. " context instead.",
  284. DeprecationWarning,
  285. stacklevel=2,
  286. )
  287. _app_ctx_stack.top.g = value
  288. def copy(self) -> "RequestContext":
  289. """Creates a copy of this request context with the same request object.
  290. This can be used to move a request context to a different greenlet.
  291. Because the actual request object is the same this cannot be used to
  292. move a request context to a different thread unless access to the
  293. request object is locked.
  294. .. versionadded:: 0.10
  295. .. versionchanged:: 1.1
  296. The current session object is used instead of reloading the original
  297. data. This prevents `flask.session` pointing to an out-of-date object.
  298. """
  299. return self.__class__(
  300. self.app,
  301. environ=self.request.environ,
  302. request=self.request,
  303. session=self.session,
  304. )
  305. def match_request(self) -> None:
  306. """Can be overridden by a subclass to hook into the matching
  307. of the request.
  308. """
  309. try:
  310. result = self.url_adapter.match(return_rule=True) # type: ignore
  311. self.request.url_rule, self.request.view_args = result # type: ignore
  312. except HTTPException as e:
  313. self.request.routing_exception = e
  314. def push(self) -> None:
  315. """Binds the request context to the current context."""
  316. # If an exception occurs in debug mode or if context preservation is
  317. # activated under exception situations exactly one context stays
  318. # on the stack. The rationale is that you want to access that
  319. # information under debug situations. However if someone forgets to
  320. # pop that context again we want to make sure that on the next push
  321. # it's invalidated, otherwise we run at risk that something leaks
  322. # memory. This is usually only a problem in test suite since this
  323. # functionality is not active in production environments.
  324. top = _request_ctx_stack.top
  325. if top is not None and top.preserved:
  326. top.pop(top._preserved_exc)
  327. # Before we push the request context we have to ensure that there
  328. # is an application context.
  329. app_ctx = _app_ctx_stack.top
  330. if app_ctx is None or app_ctx.app != self.app:
  331. app_ctx = self.app.app_context()
  332. app_ctx.push()
  333. self._implicit_app_ctx_stack.append(app_ctx)
  334. else:
  335. self._implicit_app_ctx_stack.append(None)
  336. _request_ctx_stack.push(self)
  337. # Open the session at the moment that the request context is available.
  338. # This allows a custom open_session method to use the request context.
  339. # Only open a new session if this is the first time the request was
  340. # pushed, otherwise stream_with_context loses the session.
  341. if self.session is None:
  342. session_interface = self.app.session_interface
  343. self.session = session_interface.open_session(self.app, self.request)
  344. if self.session is None:
  345. self.session = session_interface.make_null_session(self.app)
  346. # Match the request URL after loading the session, so that the
  347. # session is available in custom URL converters.
  348. if self.url_adapter is not None:
  349. self.match_request()
  350. def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
  351. """Pops the request context and unbinds it by doing that. This will
  352. also trigger the execution of functions registered by the
  353. :meth:`~flask.Flask.teardown_request` decorator.
  354. .. versionchanged:: 0.9
  355. Added the `exc` argument.
  356. """
  357. app_ctx = self._implicit_app_ctx_stack.pop()
  358. clear_request = False
  359. try:
  360. if not self._implicit_app_ctx_stack:
  361. self.preserved = False
  362. self._preserved_exc = None
  363. if exc is _sentinel:
  364. exc = sys.exc_info()[1]
  365. self.app.do_teardown_request(exc)
  366. request_close = getattr(self.request, "close", None)
  367. if request_close is not None:
  368. request_close()
  369. clear_request = True
  370. finally:
  371. rv = _request_ctx_stack.pop()
  372. # get rid of circular dependencies at the end of the request
  373. # so that we don't require the GC to be active.
  374. if clear_request:
  375. rv.request.environ["werkzeug.request"] = None
  376. # Get rid of the app as well if necessary.
  377. if app_ctx is not None:
  378. app_ctx.pop(exc)
  379. assert (
  380. rv is self
  381. ), f"Popped wrong request context. ({rv!r} instead of {self!r})"
  382. def auto_pop(self, exc: t.Optional[BaseException]) -> None:
  383. if self.request.environ.get("flask._preserve_context") or (
  384. exc is not None and self.app.preserve_context_on_exception
  385. ):
  386. self.preserved = True
  387. self._preserved_exc = exc # type: ignore
  388. else:
  389. self.pop(exc)
  390. def __enter__(self) -> "RequestContext":
  391. self.push()
  392. return self
  393. def __exit__(
  394. self,
  395. exc_type: t.Optional[type],
  396. exc_value: t.Optional[BaseException],
  397. tb: t.Optional[TracebackType],
  398. ) -> None:
  399. # do not pop the request stack if we are in debug mode and an
  400. # exception happened. This will allow the debugger to still
  401. # access the request object in the interactive shell. Furthermore
  402. # the context can be force kept alive for the test client.
  403. # See flask.testing for how this works.
  404. self.auto_pop(exc_value)
  405. def __repr__(self) -> str:
  406. return (
  407. f"<{type(self).__name__} {self.request.url!r}"
  408. f" [{self.request.method}] of {self.app.name}>"
  409. )