ctx.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.ctx
  4. ~~~~~~~~~
  5. Implements the objects required to keep the context.
  6. :copyright: (c) 2015 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import sys
  10. from functools import update_wrapper
  11. from werkzeug.exceptions import HTTPException
  12. from .globals import _request_ctx_stack, _app_ctx_stack
  13. from .signals import appcontext_pushed, appcontext_popped
  14. from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise
  15. # a singleton sentinel value for parameter defaults
  16. _sentinel = object()
  17. class _AppCtxGlobals(object):
  18. """A plain object."""
  19. def get(self, name, default=None):
  20. return self.__dict__.get(name, default)
  21. def pop(self, name, default=_sentinel):
  22. if default is _sentinel:
  23. return self.__dict__.pop(name)
  24. else:
  25. return self.__dict__.pop(name, default)
  26. def setdefault(self, name, default=None):
  27. return self.__dict__.setdefault(name, default)
  28. def __contains__(self, item):
  29. return item in self.__dict__
  30. def __iter__(self):
  31. return iter(self.__dict__)
  32. def __repr__(self):
  33. top = _app_ctx_stack.top
  34. if top is not None:
  35. return '<flask.g of %r>' % top.app.name
  36. return object.__repr__(self)
  37. def after_this_request(f):
  38. """Executes a function after this request. This is useful to modify
  39. response objects. The function is passed the response object and has
  40. to return the same or a new one.
  41. Example::
  42. @app.route('/')
  43. def index():
  44. @after_this_request
  45. def add_header(response):
  46. response.headers['X-Foo'] = 'Parachute'
  47. return response
  48. return 'Hello World!'
  49. This is more useful if a function other than the view function wants to
  50. modify a response. For instance think of a decorator that wants to add
  51. some headers without converting the return value into a response object.
  52. .. versionadded:: 0.9
  53. """
  54. _request_ctx_stack.top._after_request_functions.append(f)
  55. return f
  56. def copy_current_request_context(f):
  57. """A helper function that decorates a function to retain the current
  58. request context. This is useful when working with greenlets. The moment
  59. the function is decorated a copy of the request context is created and
  60. then pushed when the function is called.
  61. Example::
  62. import gevent
  63. from flask import copy_current_request_context
  64. @app.route('/')
  65. def index():
  66. @copy_current_request_context
  67. def do_some_work():
  68. # do some work here, it can access flask.request like you
  69. # would otherwise in the view function.
  70. ...
  71. gevent.spawn(do_some_work)
  72. return 'Regular response'
  73. .. versionadded:: 0.10
  74. """
  75. top = _request_ctx_stack.top
  76. if top is None:
  77. raise RuntimeError('This decorator can only be used at local scopes '
  78. 'when a request context is on the stack. For instance within '
  79. 'view functions.')
  80. reqctx = top.copy()
  81. def wrapper(*args, **kwargs):
  82. with reqctx:
  83. return f(*args, **kwargs)
  84. return update_wrapper(wrapper, f)
  85. def has_request_context():
  86. """If you have code that wants to test if a request context is there or
  87. not this function can be used. For instance, you may want to take advantage
  88. of request information if the request object is available, but fail
  89. silently if it is unavailable.
  90. ::
  91. class User(db.Model):
  92. def __init__(self, username, remote_addr=None):
  93. self.username = username
  94. if remote_addr is None and has_request_context():
  95. remote_addr = request.remote_addr
  96. self.remote_addr = remote_addr
  97. Alternatively you can also just test any of the context bound objects
  98. (such as :class:`request` or :class:`g` for truthness)::
  99. class User(db.Model):
  100. def __init__(self, username, remote_addr=None):
  101. self.username = username
  102. if remote_addr is None and request:
  103. remote_addr = request.remote_addr
  104. self.remote_addr = remote_addr
  105. .. versionadded:: 0.7
  106. """
  107. return _request_ctx_stack.top is not None
  108. def has_app_context():
  109. """Works like :func:`has_request_context` but for the application
  110. context. You can also just do a boolean check on the
  111. :data:`current_app` object instead.
  112. .. versionadded:: 0.9
  113. """
  114. return _app_ctx_stack.top is not None
  115. class AppContext(object):
  116. """The application context binds an application object implicitly
  117. to the current thread or greenlet, similar to how the
  118. :class:`RequestContext` binds request information. The application
  119. context is also implicitly created if a request context is created
  120. but the application is not on top of the individual application
  121. context.
  122. """
  123. def __init__(self, app):
  124. self.app = app
  125. self.url_adapter = app.create_url_adapter(None)
  126. self.g = app.app_ctx_globals_class()
  127. # Like request context, app contexts can be pushed multiple times
  128. # but there a basic "refcount" is enough to track them.
  129. self._refcnt = 0
  130. def push(self):
  131. """Binds the app context to the current context."""
  132. self._refcnt += 1
  133. if hasattr(sys, 'exc_clear'):
  134. sys.exc_clear()
  135. _app_ctx_stack.push(self)
  136. appcontext_pushed.send(self.app)
  137. def pop(self, exc=_sentinel):
  138. """Pops the app context."""
  139. try:
  140. self._refcnt -= 1
  141. if self._refcnt <= 0:
  142. if exc is _sentinel:
  143. exc = sys.exc_info()[1]
  144. self.app.do_teardown_appcontext(exc)
  145. finally:
  146. rv = _app_ctx_stack.pop()
  147. assert rv is self, 'Popped wrong app context. (%r instead of %r)' \
  148. % (rv, self)
  149. appcontext_popped.send(self.app)
  150. def __enter__(self):
  151. self.push()
  152. return self
  153. def __exit__(self, exc_type, exc_value, tb):
  154. self.pop(exc_value)
  155. if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:
  156. reraise(exc_type, exc_value, tb)
  157. class RequestContext(object):
  158. """The request context contains all request relevant information. It is
  159. created at the beginning of the request and pushed to the
  160. `_request_ctx_stack` and removed at the end of it. It will create the
  161. URL adapter and request object for the WSGI environment provided.
  162. Do not attempt to use this class directly, instead use
  163. :meth:`~flask.Flask.test_request_context` and
  164. :meth:`~flask.Flask.request_context` to create this object.
  165. When the request context is popped, it will evaluate all the
  166. functions registered on the application for teardown execution
  167. (:meth:`~flask.Flask.teardown_request`).
  168. The request context is automatically popped at the end of the request
  169. for you. In debug mode the request context is kept around if
  170. exceptions happen so that interactive debuggers have a chance to
  171. introspect the data. With 0.4 this can also be forced for requests
  172. that did not fail and outside of ``DEBUG`` mode. By setting
  173. ``'flask._preserve_context'`` to ``True`` on the WSGI environment the
  174. context will not pop itself at the end of the request. This is used by
  175. the :meth:`~flask.Flask.test_client` for example to implement the
  176. deferred cleanup functionality.
  177. You might find this helpful for unittests where you need the
  178. information from the context local around for a little longer. Make
  179. sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in
  180. that situation, otherwise your unittests will leak memory.
  181. """
  182. def __init__(self, app, environ, request=None):
  183. self.app = app
  184. if request is None:
  185. request = app.request_class(environ)
  186. self.request = request
  187. self.url_adapter = app.create_url_adapter(self.request)
  188. self.flashes = None
  189. self.session = None
  190. # Request contexts can be pushed multiple times and interleaved with
  191. # other request contexts. Now only if the last level is popped we
  192. # get rid of them. Additionally if an application context is missing
  193. # one is created implicitly so for each level we add this information
  194. self._implicit_app_ctx_stack = []
  195. # indicator if the context was preserved. Next time another context
  196. # is pushed the preserved context is popped.
  197. self.preserved = False
  198. # remembers the exception for pop if there is one in case the context
  199. # preservation kicks in.
  200. self._preserved_exc = None
  201. # Functions that should be executed after the request on the response
  202. # object. These will be called before the regular "after_request"
  203. # functions.
  204. self._after_request_functions = []
  205. self.match_request()
  206. def _get_g(self):
  207. return _app_ctx_stack.top.g
  208. def _set_g(self, value):
  209. _app_ctx_stack.top.g = value
  210. g = property(_get_g, _set_g)
  211. del _get_g, _set_g
  212. def copy(self):
  213. """Creates a copy of this request context with the same request object.
  214. This can be used to move a request context to a different greenlet.
  215. Because the actual request object is the same this cannot be used to
  216. move a request context to a different thread unless access to the
  217. request object is locked.
  218. .. versionadded:: 0.10
  219. """
  220. return self.__class__(self.app,
  221. environ=self.request.environ,
  222. request=self.request
  223. )
  224. def match_request(self):
  225. """Can be overridden by a subclass to hook into the matching
  226. of the request.
  227. """
  228. try:
  229. url_rule, self.request.view_args = \
  230. self.url_adapter.match(return_rule=True)
  231. self.request.url_rule = url_rule
  232. except HTTPException as e:
  233. self.request.routing_exception = e
  234. def push(self):
  235. """Binds the request context to the current context."""
  236. # If an exception occurs in debug mode or if context preservation is
  237. # activated under exception situations exactly one context stays
  238. # on the stack. The rationale is that you want to access that
  239. # information under debug situations. However if someone forgets to
  240. # pop that context again we want to make sure that on the next push
  241. # it's invalidated, otherwise we run at risk that something leaks
  242. # memory. This is usually only a problem in test suite since this
  243. # functionality is not active in production environments.
  244. top = _request_ctx_stack.top
  245. if top is not None and top.preserved:
  246. top.pop(top._preserved_exc)
  247. # Before we push the request context we have to ensure that there
  248. # is an application context.
  249. app_ctx = _app_ctx_stack.top
  250. if app_ctx is None or app_ctx.app != self.app:
  251. app_ctx = self.app.app_context()
  252. app_ctx.push()
  253. self._implicit_app_ctx_stack.append(app_ctx)
  254. else:
  255. self._implicit_app_ctx_stack.append(None)
  256. if hasattr(sys, 'exc_clear'):
  257. sys.exc_clear()
  258. _request_ctx_stack.push(self)
  259. # Open the session at the moment that the request context is
  260. # available. This allows a custom open_session method to use the
  261. # request context (e.g. code that access database information
  262. # stored on `g` instead of the appcontext).
  263. self.session = self.app.open_session(self.request)
  264. if self.session is None:
  265. self.session = self.app.make_null_session()
  266. def pop(self, exc=_sentinel):
  267. """Pops the request context and unbinds it by doing that. This will
  268. also trigger the execution of functions registered by the
  269. :meth:`~flask.Flask.teardown_request` decorator.
  270. .. versionchanged:: 0.9
  271. Added the `exc` argument.
  272. """
  273. app_ctx = self._implicit_app_ctx_stack.pop()
  274. try:
  275. clear_request = False
  276. if not self._implicit_app_ctx_stack:
  277. self.preserved = False
  278. self._preserved_exc = None
  279. if exc is _sentinel:
  280. exc = sys.exc_info()[1]
  281. self.app.do_teardown_request(exc)
  282. # If this interpreter supports clearing the exception information
  283. # we do that now. This will only go into effect on Python 2.x,
  284. # on 3.x it disappears automatically at the end of the exception
  285. # stack.
  286. if hasattr(sys, 'exc_clear'):
  287. sys.exc_clear()
  288. request_close = getattr(self.request, 'close', None)
  289. if request_close is not None:
  290. request_close()
  291. clear_request = True
  292. finally:
  293. rv = _request_ctx_stack.pop()
  294. # get rid of circular dependencies at the end of the request
  295. # so that we don't require the GC to be active.
  296. if clear_request:
  297. rv.request.environ['werkzeug.request'] = None
  298. # Get rid of the app as well if necessary.
  299. if app_ctx is not None:
  300. app_ctx.pop(exc)
  301. assert rv is self, 'Popped wrong request context. ' \
  302. '(%r instead of %r)' % (rv, self)
  303. def auto_pop(self, exc):
  304. if self.request.environ.get('flask._preserve_context') or \
  305. (exc is not None and self.app.preserve_context_on_exception):
  306. self.preserved = True
  307. self._preserved_exc = exc
  308. else:
  309. self.pop(exc)
  310. def __enter__(self):
  311. self.push()
  312. return self
  313. def __exit__(self, exc_type, exc_value, tb):
  314. # do not pop the request stack if we are in debug mode and an
  315. # exception happened. This will allow the debugger to still
  316. # access the request object in the interactive shell. Furthermore
  317. # the context can be force kept alive for the test client.
  318. # See flask.testing for how this works.
  319. self.auto_pop(exc_value)
  320. if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:
  321. reraise(exc_type, exc_value, tb)
  322. def __repr__(self):
  323. return '<%s \'%s\' [%s] of %s>' % (
  324. self.__class__.__name__,
  325. self.request.url,
  326. self.request.method,
  327. self.app.name,
  328. )