You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

481 lines
17KB

  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 .globals import _app_ctx_stack
  7. from .globals import _request_ctx_stack
  8. from .signals import appcontext_popped
  9. from .signals import appcontext_pushed
  10. from .typing import AfterRequestCallable
  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: AfterRequestCallable) -> 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. _request_ctx_stack.top._after_request_functions.append(f)
  98. return f
  99. def copy_current_request_context(f: t.Callable) -> t.Callable:
  100. """A helper function that decorates a function to retain the current
  101. request context. This is useful when working with greenlets. The moment
  102. the function is decorated a copy of the request context is created and
  103. then pushed when the function is called. The current session is also
  104. included in the copied request context.
  105. Example::
  106. import gevent
  107. from flask import copy_current_request_context
  108. @app.route('/')
  109. def index():
  110. @copy_current_request_context
  111. def do_some_work():
  112. # do some work here, it can access flask.request or
  113. # flask.session like you would otherwise in the view function.
  114. ...
  115. gevent.spawn(do_some_work)
  116. return 'Regular response'
  117. .. versionadded:: 0.10
  118. """
  119. top = _request_ctx_stack.top
  120. if top is None:
  121. raise RuntimeError(
  122. "This decorator can only be used at local scopes "
  123. "when a request context is on the stack. For instance within "
  124. "view functions."
  125. )
  126. reqctx = top.copy()
  127. def wrapper(*args, **kwargs):
  128. with reqctx:
  129. return f(*args, **kwargs)
  130. return update_wrapper(wrapper, f)
  131. def has_request_context() -> bool:
  132. """If you have code that wants to test if a request context is there or
  133. not this function can be used. For instance, you may want to take advantage
  134. of request information if the request object is available, but fail
  135. silently if it is unavailable.
  136. ::
  137. class User(db.Model):
  138. def __init__(self, username, remote_addr=None):
  139. self.username = username
  140. if remote_addr is None and has_request_context():
  141. remote_addr = request.remote_addr
  142. self.remote_addr = remote_addr
  143. Alternatively you can also just test any of the context bound objects
  144. (such as :class:`request` or :class:`g`) for truthness::
  145. class User(db.Model):
  146. def __init__(self, username, remote_addr=None):
  147. self.username = username
  148. if remote_addr is None and request:
  149. remote_addr = request.remote_addr
  150. self.remote_addr = remote_addr
  151. .. versionadded:: 0.7
  152. """
  153. return _request_ctx_stack.top is not None
  154. def has_app_context() -> bool:
  155. """Works like :func:`has_request_context` but for the application
  156. context. You can also just do a boolean check on the
  157. :data:`current_app` object instead.
  158. .. versionadded:: 0.9
  159. """
  160. return _app_ctx_stack.top is not None
  161. class AppContext:
  162. """The application context binds an application object implicitly
  163. to the current thread or greenlet, similar to how the
  164. :class:`RequestContext` binds request information. The application
  165. context is also implicitly created if a request context is created
  166. but the application is not on top of the individual application
  167. context.
  168. """
  169. def __init__(self, app: "Flask") -> None:
  170. self.app = app
  171. self.url_adapter = app.create_url_adapter(None)
  172. self.g = app.app_ctx_globals_class()
  173. # Like request context, app contexts can be pushed multiple times
  174. # but there a basic "refcount" is enough to track them.
  175. self._refcnt = 0
  176. def push(self) -> None:
  177. """Binds the app context to the current context."""
  178. self._refcnt += 1
  179. _app_ctx_stack.push(self)
  180. appcontext_pushed.send(self.app)
  181. def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
  182. """Pops the app context."""
  183. try:
  184. self._refcnt -= 1
  185. if self._refcnt <= 0:
  186. if exc is _sentinel:
  187. exc = sys.exc_info()[1]
  188. self.app.do_teardown_appcontext(exc)
  189. finally:
  190. rv = _app_ctx_stack.pop()
  191. assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"
  192. appcontext_popped.send(self.app)
  193. def __enter__(self) -> "AppContext":
  194. self.push()
  195. return self
  196. def __exit__(
  197. self, exc_type: type, exc_value: BaseException, tb: TracebackType
  198. ) -> None:
  199. self.pop(exc_value)
  200. class RequestContext:
  201. """The request context contains all request relevant information. It is
  202. created at the beginning of the request and pushed to the
  203. `_request_ctx_stack` and removed at the end of it. It will create the
  204. URL adapter and request object for the WSGI environment provided.
  205. Do not attempt to use this class directly, instead use
  206. :meth:`~flask.Flask.test_request_context` and
  207. :meth:`~flask.Flask.request_context` to create this object.
  208. When the request context is popped, it will evaluate all the
  209. functions registered on the application for teardown execution
  210. (:meth:`~flask.Flask.teardown_request`).
  211. The request context is automatically popped at the end of the request
  212. for you. In debug mode the request context is kept around if
  213. exceptions happen so that interactive debuggers have a chance to
  214. introspect the data. With 0.4 this can also be forced for requests
  215. that did not fail and outside of ``DEBUG`` mode. By setting
  216. ``'flask._preserve_context'`` to ``True`` on the WSGI environment the
  217. context will not pop itself at the end of the request. This is used by
  218. the :meth:`~flask.Flask.test_client` for example to implement the
  219. deferred cleanup functionality.
  220. You might find this helpful for unittests where you need the
  221. information from the context local around for a little longer. Make
  222. sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in
  223. that situation, otherwise your unittests will leak memory.
  224. """
  225. def __init__(
  226. self,
  227. app: "Flask",
  228. environ: dict,
  229. request: t.Optional["Request"] = None,
  230. session: t.Optional["SessionMixin"] = None,
  231. ) -> None:
  232. self.app = app
  233. if request is None:
  234. request = app.request_class(environ)
  235. self.request = request
  236. self.url_adapter = None
  237. try:
  238. self.url_adapter = app.create_url_adapter(self.request)
  239. except HTTPException as e:
  240. self.request.routing_exception = e
  241. self.flashes = None
  242. self.session = session
  243. # Request contexts can be pushed multiple times and interleaved with
  244. # other request contexts. Now only if the last level is popped we
  245. # get rid of them. Additionally if an application context is missing
  246. # one is created implicitly so for each level we add this information
  247. self._implicit_app_ctx_stack: t.List[t.Optional["AppContext"]] = []
  248. # indicator if the context was preserved. Next time another context
  249. # is pushed the preserved context is popped.
  250. self.preserved = False
  251. # remembers the exception for pop if there is one in case the context
  252. # preservation kicks in.
  253. self._preserved_exc = None
  254. # Functions that should be executed after the request on the response
  255. # object. These will be called before the regular "after_request"
  256. # functions.
  257. self._after_request_functions: t.List[AfterRequestCallable] = []
  258. @property
  259. def g(self) -> AppContext:
  260. return _app_ctx_stack.top.g
  261. @g.setter
  262. def g(self, value: AppContext) -> None:
  263. _app_ctx_stack.top.g = value
  264. def copy(self) -> "RequestContext":
  265. """Creates a copy of this request context with the same request object.
  266. This can be used to move a request context to a different greenlet.
  267. Because the actual request object is the same this cannot be used to
  268. move a request context to a different thread unless access to the
  269. request object is locked.
  270. .. versionadded:: 0.10
  271. .. versionchanged:: 1.1
  272. The current session object is used instead of reloading the original
  273. data. This prevents `flask.session` pointing to an out-of-date object.
  274. """
  275. return self.__class__(
  276. self.app,
  277. environ=self.request.environ,
  278. request=self.request,
  279. session=self.session,
  280. )
  281. def match_request(self) -> None:
  282. """Can be overridden by a subclass to hook into the matching
  283. of the request.
  284. """
  285. try:
  286. result = self.url_adapter.match(return_rule=True) # type: ignore
  287. self.request.url_rule, self.request.view_args = result # type: ignore
  288. except HTTPException as e:
  289. self.request.routing_exception = e
  290. def push(self) -> None:
  291. """Binds the request context to the current context."""
  292. # If an exception occurs in debug mode or if context preservation is
  293. # activated under exception situations exactly one context stays
  294. # on the stack. The rationale is that you want to access that
  295. # information under debug situations. However if someone forgets to
  296. # pop that context again we want to make sure that on the next push
  297. # it's invalidated, otherwise we run at risk that something leaks
  298. # memory. This is usually only a problem in test suite since this
  299. # functionality is not active in production environments.
  300. top = _request_ctx_stack.top
  301. if top is not None and top.preserved:
  302. top.pop(top._preserved_exc)
  303. # Before we push the request context we have to ensure that there
  304. # is an application context.
  305. app_ctx = _app_ctx_stack.top
  306. if app_ctx is None or app_ctx.app != self.app:
  307. app_ctx = self.app.app_context()
  308. app_ctx.push()
  309. self._implicit_app_ctx_stack.append(app_ctx)
  310. else:
  311. self._implicit_app_ctx_stack.append(None)
  312. _request_ctx_stack.push(self)
  313. # Open the session at the moment that the request context is available.
  314. # This allows a custom open_session method to use the request context.
  315. # Only open a new session if this is the first time the request was
  316. # pushed, otherwise stream_with_context loses the session.
  317. if self.session is None:
  318. session_interface = self.app.session_interface
  319. self.session = session_interface.open_session(self.app, self.request)
  320. if self.session is None:
  321. self.session = session_interface.make_null_session(self.app)
  322. # Match the request URL after loading the session, so that the
  323. # session is available in custom URL converters.
  324. if self.url_adapter is not None:
  325. self.match_request()
  326. def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
  327. """Pops the request context and unbinds it by doing that. This will
  328. also trigger the execution of functions registered by the
  329. :meth:`~flask.Flask.teardown_request` decorator.
  330. .. versionchanged:: 0.9
  331. Added the `exc` argument.
  332. """
  333. app_ctx = self._implicit_app_ctx_stack.pop()
  334. clear_request = False
  335. try:
  336. if not self._implicit_app_ctx_stack:
  337. self.preserved = False
  338. self._preserved_exc = None
  339. if exc is _sentinel:
  340. exc = sys.exc_info()[1]
  341. self.app.do_teardown_request(exc)
  342. request_close = getattr(self.request, "close", None)
  343. if request_close is not None:
  344. request_close()
  345. clear_request = True
  346. finally:
  347. rv = _request_ctx_stack.pop()
  348. # get rid of circular dependencies at the end of the request
  349. # so that we don't require the GC to be active.
  350. if clear_request:
  351. rv.request.environ["werkzeug.request"] = None
  352. # Get rid of the app as well if necessary.
  353. if app_ctx is not None:
  354. app_ctx.pop(exc)
  355. assert (
  356. rv is self
  357. ), f"Popped wrong request context. ({rv!r} instead of {self!r})"
  358. def auto_pop(self, exc: t.Optional[BaseException]) -> None:
  359. if self.request.environ.get("flask._preserve_context") or (
  360. exc is not None and self.app.preserve_context_on_exception
  361. ):
  362. self.preserved = True
  363. self._preserved_exc = exc # type: ignore
  364. else:
  365. self.pop(exc)
  366. def __enter__(self) -> "RequestContext":
  367. self.push()
  368. return self
  369. def __exit__(
  370. self, exc_type: type, exc_value: BaseException, tb: TracebackType
  371. ) -> None:
  372. # do not pop the request stack if we are in debug mode and an
  373. # exception happened. This will allow the debugger to still
  374. # access the request object in the interactive shell. Furthermore
  375. # the context can be force kept alive for the test client.
  376. # See flask.testing for how this works.
  377. self.auto_pop(exc_value)
  378. def __repr__(self) -> str:
  379. return (
  380. f"<{type(self).__name__} {self.request.url!r}"
  381. f" [{self.request.method}] of {self.app.name}>"
  382. )