Skip to content
Myr

Merge pull request #4682 from pallets/refactor-context-stack

Before adoption: this commit came in with the history the project adopted, so no landing records it.

remove use of `LocalStack`

authored by David Lord · committed by GitHub · parents c757882, e0dad45 · Browse files · 23 files+344 added−345 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

23 files+344 added−345 removed

  • tests:+44 added−50 removed
  • other:+300 added−295 removed

23 files+344 added−345 removed

modified:docs/patterns/sqlite3.rst-4 removed
28 unmodified lines
29or create an application context itself. At that point the ``get_db``30function can be used to get the current database connection. Whenever the31context is destroyed the database connection will be terminated.3233Note: if you use Flask 0.9 or older you need to use34``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g`35object was bound to the request and not application context.3633Example::3435 @app.route('/')36 def index():
111 unmodified lines
modified:docs/api.rst+14 added-42 removed
309 unmodified lines
310311.. autoclass:: flask.ctx.RequestContext312 :members:313314.. data:: _request_ctx_stack314.. data:: flask.globals.request_ctx315316 The internal :class:`~werkzeug.local.LocalStack` that holds317 :class:`~flask.ctx.RequestContext` instances. Typically, the318 :data:`request` and :data:`session` proxies should be accessed319 instead of the stack. It may be useful to access the stack in320 extension code.316 The current :class:`~flask.ctx.RequestContext`. If a request context317 is not active, accessing attributes on this proxy will raise a318 ``RuntimeError``.319322 The following attributes are always present on each layer of the323 stack:320 This is an internal object that is essential to how Flask handles321 requests. Accessing this should not be needed in most cases. Most322 likely you want :data:`request` and :data:`session` instead.323325 `app`326 the active Flask application.327328 `url_adapter`329 the URL adapter that was used to match the request.330331 `request`332 the current request object.333334 `session`335 the active session object.336337 `g`338 an object with all the attributes of the :data:`flask.g` object.339340 `flashes`341 an internal cache for the flashed messages.342343 Example usage::344345 from flask import _request_ctx_stack346347 def get_session():348 ctx = _request_ctx_stack.top349 if ctx is not None:350 return ctx.session351324.. autoclass:: flask.ctx.AppContext325 :members:326355.. data:: _app_ctx_stack327.. data:: flask.globals.app_ctx328357 The internal :class:`~werkzeug.local.LocalStack` that holds358 :class:`~flask.ctx.AppContext` instances. Typically, the359 :data:`current_app` and :data:`g` proxies should be accessed instead360 of the stack. Extensions can access the contexts on the stack as a361 namespace to store data.329 The current :class:`~flask.ctx.AppContext`. If an app context is not330 active, accessing attributes on this proxy will raise a331 ``RuntimeError``.332363 .. versionadded:: 0.9333 This is an internal object that is essential to how Flask handles334 requests. Accessing this should not be needed in most cases. Most335 likely you want :data:`current_app` and :data:`g` instead.336337.. autoclass:: flask.blueprints.BlueprintSetupState338 :members:339
410 unmodified lines
modified:docs/appcontext.rst-8 removed
134 unmodified lines
135136Accessing ``db`` will call ``get_db`` internally, in the same way that137:data:`current_app` works.138139----139141If you're writing an extension, :data:`g` should be reserved for user142code. You may store internal data on the context itself, but be sure to143use a sufficiently unique name. The current context is accessed with144:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see145:doc:`/extensiondev`.146147140Events and Signals141------------------142143The application will call functions registered with
6 unmodified lines
modified:docs/extensiondev.rst-6 removed
185 unmodified lines
186when the application context ends. If it should only be valid during a187request, or would not be used in the CLI outside a reqeust, use188:meth:`~flask.Flask.teardown_request`.189190An older technique for storing context data was to store it on191``_app_ctx_stack.top`` or ``_request_ctx_stack.top``. However, this just192moves the same namespace collision problem elsewhere (although less193likely) and modifies objects that are very internal to Flask's194operations. Prefer storing data under a unique name in ``g``.190196191Views and Models192----------------193194Your extension views might want to interact with specific models in your
110 unmodified lines
modified:docs/reqcontext.rst+13 added-12 removed
35 unmodified lines
36context, which also pushes an :doc:`app context </appcontext>`. When the37request ends it pops the request context then the application context.3839The context is unique to each thread (or other worker type).40:data:`request` cannot be passed to another thread, the other thread41will have a different context stack and will not know about the request42the parent thread was pointing to.40:data:`request` cannot be passed to another thread, the other thread has41a different context space and will not know about the request the parent42thread was pointing to.4344Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`45for more information on how this works internally.44Context locals are implemented using Python's :mod:`contextvars` and45Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46lifetime of context vars automatically, and local proxy wraps that47low-level interface to make the data easier to work with.484950Manually Push a Context51-----------------------
36 unmodified lines
88---------------------8990The :meth:`Flask.wsgi_app` method is called to handle each request. It91manages the contexts during the request. Internally, the request and90application contexts work as stacks, :data:`_request_ctx_stack` and91:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the92application contexts work like stacks. When contexts are pushed, the93proxies that depend on them are available and point at information from93the top context on the stack.94the top item.9596When the request starts, a :class:`~ctx.RequestContext` is created and97pushed, which creates and pushes an :class:`~ctx.AppContext` first if98a context for that application is not already the top context. While99these contexts are pushed, the :data:`current_app`, :data:`g`,100:data:`request`, and :data:`session` proxies are available to the101original thread handling the request.102102Because the contexts are stacks, other contexts may be pushed to change103the proxies during a request. While this is not a common pattern, it104can be used in advanced applications to, for example, do internal105redirects or chain different applications together.103Other contexts may be pushed to change the proxies during a request.104While this is not a common pattern, it can be used in advanced105applications to, for example, do internal redirects or chain different106applications together.107108After the request is dispatched and a response is generated and sent,109the request context is popped, which then pops the application context.110Immediately before they are popped, the :meth:`~Flask.teardown_request`
137 unmodified lines
modified:src/flask/__init__.py+26 added-2 removed
9 unmodified lines
10from .ctx import after_this_request as after_this_request11from .ctx import copy_current_request_context as copy_current_request_context12from .ctx import has_app_context as has_app_context13from .ctx import has_request_context as has_request_context14from .globals import _app_ctx_stack as _app_ctx_stack15from .globals import _request_ctx_stack as _request_ctx_stack14from .globals import current_app as current_app15from .globals import g as g16from .globals import request as request17from .globals import session as session
24 unmodified lines
42from .templating import stream_template as stream_template43from .templating import stream_template_string as stream_template_string4445__version__ = "2.2.0.dev0"464748def __getattr__(name):49 if name == "_app_ctx_stack":50 import warnings51 from .globals import __app_ctx_stack5253 warnings.warn(54 "'_app_ctx_stack' is deprecated and will be removed in Flask 2.3.",55 DeprecationWarning,56 stacklevel=2,57 )58 return __app_ctx_stack5960 if name == "_request_ctx_stack":61 import warnings62 from .globals import __request_ctx_stack6364 warnings.warn(65 "'_request_ctx_stack' is deprecated and will be removed in Flask 2.3.",66 DeprecationWarning,67 stacklevel=2,68 )69 return __request_ctx_stack7071 raise AttributeError(name)
modified:src/flask/app.py+34 added-31 removed
36 unmodified lines
37from .config import ConfigAttribute38from .ctx import _AppCtxGlobals39from .ctx import AppContext40from .ctx import RequestContext41from .globals import _app_ctx_stack42from .globals import _request_ctx_stack41from .globals import _cv_app42from .globals import _cv_req43from .globals import g44from .globals import request45from .globals import request_ctx46from .globals import session47from .helpers import _split_blueprint_path48from .helpers import get_debug_flag49from .helpers import get_env
1233 unmodified lines
1283 return f12841285 @setupmethod1286 def teardown_appcontext(self, f: T_teardown) -> T_teardown:1286 """Registers a function to be called when the application context1287 ends. These functions are typically also called when the request1288 context is popped.1287 """Registers a function to be called when the application1288 context is popped. The application context is typically popped1289 after the request context for each request, at the end of CLI1290 commands, or after a manually pushed context ends.12911290 Example::1292 .. code-block:: python12931292 ctx = app.app_context()1293 ctx.push()1294 ...1295 ctx.pop()1294 with app.app_context():1295 ...12961297 When ``ctx.pop()`` is executed in the above example, the teardown1298 functions are called just before the app context moves from the1299 stack of active contexts. This becomes relevant if you are using1300 such constructs in tests.1297 When the ``with`` block exits (or ``ctx.pop()`` is called), the1298 teardown functions are called just before the app context is1299 made inactive. Since a request context typically also manages an1300 application context it would also be called when you pop a1301 request context.13021302 Since a request context typically also manages an application1303 context it would also be called when you pop a request context.1303 When a teardown function was called because of an unhandled1304 exception it will be passed an error object. If an1305 :meth:`errorhandler` is registered, it will handle the exception1306 and the teardown will not receive it.13071305 When a teardown function was called because of an unhandled exception1306 it will be passed an error object. If an :meth:`errorhandler` is1307 registered, it will handle the exception and the teardown will not1308 receive it.1308 Teardown functions must avoid raising exceptions. If they1309 execute code that might fail they must surround that code with a1310 ``try``/``except`` block and log any errors.13111312 The return values of teardown functions are ignored.13131314 .. versionadded:: 0.9
240 unmodified lines
1555 .. versionchanged:: 0.71556 This no longer does the exception handling, this code was1557 moved to the new :meth:`full_dispatch_request`.1558 """1557 req = _request_ctx_stack.top.request1559 req = request_ctx.request1560 if req.routing_exception is not None:1561 self.raise_routing_exception(req)1560 rule = req.url_rule1562 rule: Rule = req.url_rule # type: ignore[assignment]1563 # if we provide automatic options for this URL and the1564 # request came with the OPTIONS method, reply automatically1565 if (1566 getattr(rule, "provide_automatic_options", False)1567 and req.method == "OPTIONS"1568 ):1569 return self.make_default_options_response()1570 # otherwise dispatch to the handler for that endpoint1571 view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment]1569 return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)1572 return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)15731574 def full_dispatch_request(self) -> Response:1575 """Dispatches the request and on top of that performs request1576 pre and postprocessing as well as HTTP exception catching and
56 unmodified lines
1633 behavior of ``OPTIONS`` responses.16341635 .. versionadded:: 0.71636 """1634 adapter = _request_ctx_stack.top.url_adapter1635 methods = adapter.allowed_methods()1637 adapter = request_ctx.url_adapter1638 methods = adapter.allowed_methods() # type: ignore[union-attr]1639 rv = self.response_class()1640 rv.allow.update(methods)1641 return rv1642
99 unmodified lines
17421743 .. versionadded:: 2.21744 Moved from ``flask.url_for``, which calls this method.1745 """1743 req_ctx = _request_ctx_stack.top1746 req_ctx = _cv_req.get(None)17471748 if req_ctx is not None:1749 url_adapter = req_ctx.url_adapter1750 blueprint_name = req_ctx.request.blueprint
10 unmodified lines
1761 # domain by default, unless a scheme is given.1762 if _external is None:1763 _external = _scheme is not None1764 else:1762 app_ctx = _app_ctx_stack.top1765 app_ctx = _cv_app.get(None)17661767 # If called by helpers.url_for, an app context is active,1768 # use its url_adapter. Otherwise, app.url_for was called1769 # directly, build an adapter.
22 unmodified lines
17921793 self.inject_url_defaults(endpoint, values)17941795 try:1793 rv = url_adapter.build(1796 rv = url_adapter.build( # type: ignore[union-attr]1797 endpoint,1798 values,1799 method=_method,1800 url_scheme=_scheme,
300 unmodified lines
2101 :param response: a :attr:`response_class` object.2102 :return: a new response object or the same, has to be an2103 instance of :attr:`response_class`.2104 """2102 ctx = _request_ctx_stack.top2105 ctx = request_ctx._get_current_object() # type: ignore[attr-defined]21062107 for func in ctx._after_request_functions:2108 response = self.ensure_sync(func)(response)2109
197 unmodified lines
2307 raise2308 return response(environ, start_response)2309 finally:2310 if "werkzeug.debug.preserve_context" in environ:2308 environ["werkzeug.debug.preserve_context"](_app_ctx_stack.top)2309 environ["werkzeug.debug.preserve_context"](_request_ctx_stack.top)2311 environ["werkzeug.debug.preserve_context"](_cv_app.get())2312 environ["werkzeug.debug.preserve_context"](_cv_req.get())23132314 if error is not None and self.should_ignore_error(error):2315 error = None2316
8 unmodified lines
modified:src/flask/cli.py+3 added-5 removed
1049 unmodified lines
1050 This is useful for executing small snippets of management code1051 without having to manually configure the application.1052 """1053 import code1054 from .globals import _app_ctx_stack10541056 app = _app_ctx_stack.top.app1055 banner = (1056 f"Python {sys.version} on {sys.platform}\n"1059 f"App: {app.import_name} [{app.env}]\n"1060 f"Instance: {app.instance_path}"1057 f"App: {current_app.import_name} [{current_app.env}]\n"1058 f"Instance: {current_app.instance_path}"1059 )1060 ctx: dict = {}10611062 # Support the regular Python interpreter startup script if someone
2 unmodified lines
1065 if startup and os.path.isfile(startup):1066 with open(startup) as f:1067 eval(compile(f.read(), startup, "exec"), ctx)10681071 ctx.update(app.make_shell_context())1069 ctx.update(current_app.make_shell_context())10701071 # Site, customize, or startup script can set a hook to call when1072 # entering interactive mode. The default one sets up readline with1073 # tab and history completion.
85 unmodified lines
modified:src/flask/ctx.py+60 added-79 removed
1import contextvars2import sys3import typing as t4from functools import update_wrapper5from types import TracebackType67from werkzeug.exceptions import HTTPException89from . import typing as ft9from .globals import _app_ctx_stack10from .globals import _request_ctx_stack10from .globals import _cv_app11from .globals import _cv_req12from .signals import appcontext_popped13from .signals import appcontext_pushed1415if t.TYPE_CHECKING: # pragma: no cover
87 unmodified lines
103 def __iter__(self) -> t.Iterator[str]:104 return iter(self.__dict__)105106 def __repr__(self) -> str:106 top = _app_ctx_stack.top107 if top is not None:108 return f"<flask.g of {top.app.name!r}>"107 ctx = _cv_app.get(None)108 if ctx is not None:109 return f"<flask.g of '{ctx.app.name}'>"110 return object.__repr__(self)111112113def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:
16 unmodified lines
130 some headers without converting the return value into a response object.131132 .. versionadded:: 0.9133 """133 top = _request_ctx_stack.top134 ctx = _cv_req.get(None)135135 if top is None:136 if ctx is None:137 raise RuntimeError(137 "This decorator can only be used when a request context is"138 " active, such as within a view function."138 "'after_this_request' can only be used when a request"139 " context is active, such as in a view function."140 )141141 top._after_request_functions.append(f)142 ctx._after_request_functions.append(f)143 return f144145146def copy_current_request_context(f: t.Callable) -> t.Callable:
19 unmodified lines
166 return 'Regular response'167168 .. versionadded:: 0.10169 """169 top = _request_ctx_stack.top170 ctx = _cv_req.get(None)171171 if top is None:172 if ctx is None:173 raise RuntimeError(173 "This decorator can only be used when a request context is"174 " active, such as within a view function."174 "'copy_current_request_context' can only be used when a"175 " request context is active, such as in a view function."176 )177177 reqctx = top.copy()178 ctx = ctx.copy()179180 def wrapper(*args, **kwargs):180 with reqctx:181 return reqctx.app.ensure_sync(f)(*args, **kwargs)181 with ctx:182 return ctx.app.ensure_sync(f)(*args, **kwargs)183184 return update_wrapper(wrapper, f)185186
25 unmodified lines
212 self.remote_addr = remote_addr213214 .. versionadded:: 0.7215 """215 return _request_ctx_stack.top is not None216 return _cv_app.get(None) is not None217218219def has_app_context() -> bool:220 """Works like :func:`has_request_context` but for the application
1 unmodified line
222 :data:`current_app` object instead.223224 .. versionadded:: 0.9225 """225 return _app_ctx_stack.top is not None226 return _cv_req.get(None) is not None227228229class AppContext:229 """The application context binds an application object implicitly230 to the current thread or greenlet, similar to how the231 :class:`RequestContext` binds request information. The application232 context is also implicitly created if a request context is created233 but the application is not on top of the individual application234 context.230 """The app context contains application-specific information. An app231 context is created and pushed at the beginning of each request if232 one is not already active. An app context is also pushed when233 running CLI commands.234 """235236 def __init__(self, app: "Flask") -> None:237 self.app = app238 self.url_adapter = app.create_url_adapter(None)240 self.g = app.app_ctx_globals_class()239 self.g: _AppCtxGlobals = app.app_ctx_globals_class()240 self._cv_tokens: t.List[contextvars.Token] = []241242 # Like request context, app contexts can be pushed multiple times243 # but there a basic "refcount" is enough to track them.244 self._refcnt = 0245242 def push(self) -> None:243 """Binds the app context to the current context."""248 self._refcnt += 1249 _app_ctx_stack.push(self)244 self._cv_tokens.append(_cv_app.set(self))245 appcontext_pushed.send(self.app)246247 def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore248 """Pops the app context."""249 try:255 self._refcnt -= 1256 if self._refcnt <= 0:250 if len(self._cv_tokens) == 1:251 if exc is _sentinel:252 exc = sys.exc_info()[1]253 self.app.do_teardown_appcontext(exc)254 finally:261 rv = _app_ctx_stack.pop()262 assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"255 ctx = _cv_app.get()256 _cv_app.reset(self._cv_tokens.pop())257258 if ctx is not self:259 raise AssertionError(260 f"Popped wrong app context. ({ctx!r} instead of {self!r})"261 )262263 appcontext_popped.send(self.app)264265 def __enter__(self) -> "AppContext":266 self.push()
8 unmodified lines
275 self.pop(exc_value)276277278class RequestContext:279 """The request context contains all request relevant information. It is280 created at the beginning of the request and pushed to the281 `_request_ctx_stack` and removed at the end of it. It will create the282 URL adapter and request object for the WSGI environment provided.279 """The request context contains per-request information. The Flask280 app creates and pushes it at the beginning of the request, then pops281 it at the end of the request. It will create the URL adapter and282 request object for the WSGI environment provided.283284 Do not attempt to use this class directly, instead use285 :meth:`~flask.Flask.test_request_context` and286 :meth:`~flask.Flask.request_context` to create this object.
19 unmodified lines
306 ) -> None:307 self.app = app308 if request is None:309 request = app.request_class(environ)310 self.request = request310 self.request: Request = request311 self.url_adapter = None312 try:313 self.url_adapter = app.create_url_adapter(self.request)314 except HTTPException as e:315 self.request.routing_exception = e316 self.flashes = None317 self.session = session318319 # Request contexts can be pushed multiple times and interleaved with320 # other request contexts. Now only if the last level is popped we321 # get rid of them. Additionally if an application context is missing322 # one is created implicitly so for each level we add this information323 self._implicit_app_ctx_stack: t.List[t.Optional["AppContext"]] = []324316 self.flashes: t.Optional[t.List[t.Tuple[str, str]]] = None317 self.session: t.Optional["SessionMixin"] = session318 # Functions that should be executed after the request on the response319 # object. These will be called before the regular "after_request"320 # functions.321 self._after_request_functions: t.List[ft.AfterRequestCallable] = []322323 self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []324325 def copy(self) -> "RequestContext":326 """Creates a copy of this request context with the same request object.327 This can be used to move a request context to a different greenlet.328 Because the actual request object is the same this cannot be used to
25 unmodified lines
354355 def push(self) -> None:356 # Before we push the request context we have to ensure that there357 # is an application context.363 app_ctx = _app_ctx_stack.top364 if app_ctx is None or app_ctx.app != self.app:358 app_ctx = _cv_app.get(None)359360 if app_ctx is None or app_ctx.app is not self.app:361 app_ctx = self.app.app_context()362 app_ctx.push()367 self._implicit_app_ctx_stack.append(app_ctx)363 else:369 self._implicit_app_ctx_stack.append(None)364 app_ctx = None365371 _request_ctx_stack.push(self)366 self._cv_tokens.append((_cv_req.set(self), app_ctx))367368 # Open the session at the moment that the request context is available.369 # This allows a custom open_session method to use the request context.370 # Only open a new session if this is the first time the request was
17 unmodified lines
388389 .. versionchanged:: 0.9390 Added the `exc` argument.391 """397 app_ctx = self._implicit_app_ctx_stack.pop()398 clear_request = False392 clear_request = len(self._cv_tokens) == 1393394 try:401 if not self._implicit_app_ctx_stack:395 if clear_request:396 if exc is _sentinel:397 exc = sys.exc_info()[1]398 self.app.do_teardown_request(exc)399400 request_close = getattr(self.request, "close", None)401 if request_close is not None:402 request_close()409 clear_request = True403 finally:411 rv = _request_ctx_stack.pop()404 ctx = _cv_req.get()405 token, app_ctx = self._cv_tokens.pop()406 _cv_req.reset(token)407408 # get rid of circular dependencies at the end of the request409 # so that we don't require the GC to be active.410 if clear_request:416 rv.request.environ["werkzeug.request"] = None411 ctx.request.environ["werkzeug.request"] = None412418 # Get rid of the app as well if necessary.413 if app_ctx is not None:414 app_ctx.pop(exc)415422 assert (423 rv is self424 ), f"Popped wrong request context. ({rv!r} instead of {self!r})"416 if ctx is not self:417 raise AssertionError(418 f"Popped wrong request context. ({ctx!r} instead of {self!r})"419 )420426 def auto_pop(self, exc: t.Optional[BaseException]) -> None:427 """428 .. deprecated:: 2.2429 Will be removed in Flask 2.3.430 """431 import warnings432433 warnings.warn(434 "'ctx.auto_pop' is deprecated and will be removed in Flask 2.3.",435 DeprecationWarning,436 stacklevel=2,437 )438 self.pop(exc)439421 def __enter__(self) -> "RequestContext":422 self.push()423 return self424
13 unmodified lines
modified:src/flask/debughelpers.py+3 added-4 removed
1import typing as t23from .app import Flask4from .blueprints import Blueprint5from .globals import _request_ctx_stack5from .globals import request_ctx678class UnexpectedUnicodeError(AssertionError, UnicodeError):9 """Raised in places where we want some better error reporting for
105 unmodified lines
115 """This should help developers understand what failed"""116 info = [f"Locating template {template!r}:"]117 total_found = 0118 blueprint = None119 reqctx = _request_ctx_stack.top120 if reqctx is not None and reqctx.request.blueprint is not None:121 blueprint = reqctx.request.blueprint119 if request_ctx and request_ctx.request.blueprint is not None:120 blueprint = request_ctx.request.blueprint121122 for idx, (loader, srcobj, triple) in enumerate(attempts):123 if isinstance(srcobj, Flask):124 src_info = f"application {srcobj.import_name!r}"
34 unmodified lines
modified:src/flask/globals.py+84 added-36 removed
1import typing as t2from functools import partial2from contextvars import ContextVar34from werkzeug.local import LocalProxy5from werkzeug.local import LocalStack56if t.TYPE_CHECKING: # pragma: no cover7 from .app import Flask8 from .ctx import _AppCtxGlobals9 from .ctx import AppContext10 from .ctx import RequestContext11 from .sessions import SessionMixin12 from .wrappers import Request1313_request_ctx_err_msg = """\14Working outside of request context.1416This typically means that you attempted to use functionality that needed17an active HTTP request. Consult the documentation on testing for18information about how to avoid this problem.\19"""20_app_ctx_err_msg = """\15class _FakeStack:16 def __init__(self, name: str, cv: ContextVar[t.Any]) -> None:17 self.name = name18 self.cv = cv1920 def _warn(self):21 import warnings2223 warnings.warn(24 f"'_{self.name}_ctx_stack' is deprecated and will be"25 " removed in Flask 2.3. Use 'g' to store data, or"26 f" '{self.name}_ctx' to access the current context.",27 DeprecationWarning,28 stacklevel=3,29 )3031 def push(self, obj: t.Any) -> None:32 self._warn()33 self.cv.set(obj)3435 def pop(self) -> t.Any:36 self._warn()37 ctx = self.cv.get(None)38 self.cv.set(None)39 return ctx4041 @property42 def top(self) -> t.Optional[t.Any]:43 self._warn()44 return self.cv.get(None)454647_no_app_msg = """\48Working outside of application context.4950This typically means that you attempted to use functionality that needed24to interface with the current application object in some way. To solve25this, set up an application context with app.app_context(). See the26documentation for more information.\51the current application. To solve this, set up an application context52with app.app_context(). See the documentation for more information.\53"""54_cv_app: ContextVar["AppContext"] = ContextVar("flask.app_ctx")55__app_ctx_stack = _FakeStack("app", _cv_app)56app_ctx: "AppContext" = LocalProxy( # type: ignore[assignment]57 _cv_app, unbound_message=_no_app_msg58)59current_app: "Flask" = LocalProxy( # type: ignore[assignment]60 _cv_app, "app", unbound_message=_no_app_msg61)62g: "_AppCtxGlobals" = LocalProxy( # type: ignore[assignment]63 _cv_app, "g", unbound_message=_no_app_msg64)6566_no_req_msg = """\67Working outside of request context.6830def _lookup_req_object(name):31 top = _request_ctx_stack.top32 if top is None:33 raise RuntimeError(_request_ctx_err_msg)34 return getattr(top, name)69This typically means that you attempted to use functionality that needed70an active HTTP request. Consult the documentation on testing for71information about how to avoid this problem.\72"""73_cv_req: ContextVar["RequestContext"] = ContextVar("flask.request_ctx")74__request_ctx_stack = _FakeStack("request", _cv_req)75request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment]76 _cv_req, unbound_message=_no_req_msg77)78request: "Request" = LocalProxy( # type: ignore[assignment]79 _cv_req, "request", unbound_message=_no_req_msg80)81session: "SessionMixin" = LocalProxy( # type: ignore[assignment]82 _cv_req, "session", unbound_message=_no_req_msg83)848537def _lookup_app_object(name):38 top = _app_ctx_stack.top39 if top is None:40 raise RuntimeError(_app_ctx_err_msg)41 return getattr(top, name)86def __getattr__(name: str) -> t.Any:87 if name == "_app_ctx_stack":88 import warnings8990 warnings.warn(91 "'_app_ctx_stack' is deprecated and will be remoevd in Flask 2.3.",92 DeprecationWarning,93 stacklevel=2,94 )95 return __app_ctx_stack9644def _find_app():45 top = _app_ctx_stack.top46 if top is None:47 raise RuntimeError(_app_ctx_err_msg)48 return top.app97 if name == "_request_ctx_stack":98 import warnings99100 warnings.warn(101 "'_request_ctx_stack' is deprecated and will be remoevd in Flask 2.3.",102 DeprecationWarning,103 stacklevel=2,104 )105 return __request_ctx_stack10651# context locals52_request_ctx_stack = LocalStack()53_app_ctx_stack = LocalStack()54current_app: "Flask" = LocalProxy(_find_app) # type: ignore55request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore56session: "SessionMixin" = LocalProxy( # type: ignore57 partial(_lookup_req_object, "session")58)59g: "_AppCtxGlobals" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore107 raise AttributeError(name)
modified:src/flask/helpers.py+8 added-8 removed
10 unmodified lines
11import werkzeug.utils12from werkzeug.exceptions import abort as _wz_abort13from werkzeug.utils import redirect as _wz_redirect1415from .globals import _request_ctx_stack15from .globals import _cv_req16from .globals import current_app17from .globals import request18from .globals import request_ctx19from .globals import session20from .signals import message_flashed2122if t.TYPE_CHECKING: # pragma: no cover
87 unmodified lines
110111 return update_wrapper(decorator, generator_or_function) # type: ignore112113 def generator() -> t.Generator:113 ctx = _request_ctx_stack.top114 ctx = _cv_req.get(None)115 if ctx is None:116 raise RuntimeError(116 "Attempted to stream with context but "117 "there was no context in the first place to keep around."117 "'stream_with_context' can only be used when a request"118 " context is active, such as in a view function."119 )120 with ctx:121 # Dummy sentinel. Has to be inside the context block or we're122 # not actually keeping the context around.
254 unmodified lines
377 :param with_categories: set to ``True`` to also receive categories.378 :param category_filter: filter of categories to limit return values. Only379 categories in the list will be returned.380 """380 flashes = _request_ctx_stack.top.flashes381 flashes = request_ctx.flashes382 if flashes is None:382 _request_ctx_stack.top.flashes = flashes = (383 session.pop("_flashes") if "_flashes" in session else []384 )383 flashes = session.pop("_flashes") if "_flashes" in session else []384 request_ctx.flashes = flashes385 if category_filter:386 flashes = list(filter(lambda f: f[0] in category_filter, flashes))387 if not with_categories:388 return [x[1] for x in flashes]
298 unmodified lines
modified:src/flask/scaffold.py+16 added-19 removed
572 unmodified lines
573 return f574575 @setupmethod576 def teardown_request(self, f: T_teardown) -> T_teardown:577 """Register a function to be run at the end of each request,578 regardless of whether there was an exception or not. These functions579 are executed when the request context is popped, even if not an580 actual request was performed.577 """Register a function to be called when the request context is578 popped. Typically this happens at the end of each request, but579 contexts may be pushed manually as well during testing.580582 Example::581 .. code-block:: python582584 ctx = app.test_request_context()585 ctx.push()586 ...587 ctx.pop()583 with app.test_request_context():584 ...585589 When ``ctx.pop()`` is executed in the above example, the teardown590 functions are called just before the request context moves from the591 stack of active contexts. This becomes relevant if you are using592 such constructs in tests.586 When the ``with`` block exits (or ``ctx.pop()`` is called), the587 teardown functions are called just before the request context is588 made inactive.589594 Teardown functions must avoid raising exceptions. If595 they execute code that might fail they596 will have to surround the execution of that code with try/except597 statements and log any errors.590 When a teardown function was called because of an unhandled591 exception it will be passed an error object. If an592 :meth:`errorhandler` is registered, it will handle the exception593 and the teardown will not receive it.594599 When a teardown function was called because of an exception it will600 be passed an error object.595 Teardown functions must avoid raising exceptions. If they596 execute code that might fail they must surround that code with a597 ``try``/``except`` block and log any errors.598599 The return values of teardown functions are ignored.600 """601 self.teardown_request_funcs.setdefault(None, []).append(f)
288 unmodified lines
modified:src/flask/templating.py+21 added-29 removed
3 unmodified lines
4from jinja2 import Environment as BaseEnvironment5from jinja2 import Template6from jinja2 import TemplateNotFound78from .globals import _app_ctx_stack9from .globals import _request_ctx_stack8from .globals import _cv_app9from .globals import _cv_req10from .globals import current_app11from .globals import request12from .helpers import stream_with_context13from .signals import before_render_template
7 unmodified lines
21def _default_template_ctx_processor() -> t.Dict[str, t.Any]:22 """Default template context processor. Injects `request`,23 `session` and `g`.24 """25 reqctx = _request_ctx_stack.top26 appctx = _app_ctx_stack.top27 rv = {}25 appctx = _cv_app.get(None)26 reqctx = _cv_req.get(None)27 rv: t.Dict[str, t.Any] = {}28 if appctx is not None:29 rv["g"] = appctx.g30 if reqctx is not None:31 rv["request"] = reqctx.request
91 unmodified lines
123124 return list(result)125126127def _render(template: Template, context: dict, app: "Flask") -> str:127def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str:128 app.update_template_context(context)129 before_render_template.send(app, template=template, context=context)130 rv = template.render(context)131 template_rendered.send(app, template=template, context=context)132 return rv
2 unmodified lines
135def render_template(136 template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],137 **context: t.Any138) -> str:138 """Renders a template from the template folder with the given139 context.139 """Render a template by name with the given context.140141 :param template_name_or_list: the name of the template to be142 rendered, or an iterable with template names143 the first one existing will be rendered144 :param context: the variables that should be available in the145 context of the template.141 :param template_name_or_list: The name of the template to render. If142 a list is given, the first name to exist will be rendered.143 :param context: The variables to make available in the template.144 """147 ctx = _app_ctx_stack.top148 ctx.app.update_template_context(context)149 return _render(150 ctx.app.jinja_env.get_or_select_template(template_name_or_list),151 context,152 ctx.app,153 )145 app = current_app._get_current_object() # type: ignore[attr-defined]146 template = app.jinja_env.get_or_select_template(template_name_or_list)147 return _render(app, template, context)148149150def render_template_string(source: str, **context: t.Any) -> str:157 """Renders a template from the given template source string158 with the given context. Template variables will be autoescaped.151 """Render a template from the given source string with the given152 context.153160 :param source: the source code of the template to be161 rendered162 :param context: the variables that should be available in the163 context of the template.154 :param source: The source code of the template to render.155 :param context: The variables to make available in the template.156 """165 ctx = _app_ctx_stack.top166 ctx.app.update_template_context(context)167 return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)157 app = current_app._get_current_object() # type: ignore[attr-defined]158 template = app.jinja_env.from_string(source)159 return _render(app, template, context)160161162def _stream(163 app: "Flask", template: Template, context: t.Dict[str, t.Any]
49 unmodified lines
modified:src/flask/testing.py+8 added-9 removed
9 unmodified lines
10from werkzeug.urls import url_parse11from werkzeug.wrappers import Request as BaseRequest1213from .cli import ScriptInfo14from .globals import _request_ctx_stack14from .globals import _cv_req15from .json import dumps as json_dumps16from .sessions import SessionMixin1718if t.TYPE_CHECKING: # pragma: no cover
74 unmodified lines
93 return json_dumps(obj, **kwargs)949596class FlaskClient(Client):97 """Works like a regular Werkzeug test client but has some knowledge about98 how Flask works to defer the cleanup of the request context stack to the99 end of a ``with`` body when used in a ``with`` statement. For general100 information about how to use this class refer to101 :class:`werkzeug.test.Client`.97 """Works like a regular Werkzeug test client but has knowledge about98 Flask's contexts to defer the cleanup of the request context until99 the end of a ``with`` block. For general information about how to100 use this class refer to :class:`werkzeug.test.Client`.101102 .. versionchanged:: 0.12103 `app.test_client()` includes preset default environment, which can be104 set after instantiation of the `app.test_client()` object in
40 unmodified lines
145 )146 app = self.application147 environ_overrides = kwargs.setdefault("environ_overrides", {})148 self.cookie_jar.inject_wsgi(environ_overrides)150 outer_reqctx = _request_ctx_stack.top149 outer_reqctx = _cv_req.get(None)150 with app.test_request_context(*args, **kwargs) as c:151 session_interface = app.session_interface152 sess = session_interface.open_session(app, c.request)153 if sess is None:
7 unmodified lines
161 # (or None) on top of this and popping it we get exactly that162 # behavior. It's important to not use the push and pop163 # methods of the actual request context object since that would164 # mean that cleanup handlers are called166 _request_ctx_stack.push(outer_reqctx)165 token = _cv_req.set(outer_reqctx) # type: ignore[arg-type]166 try:167 yield sess168 finally:170 _request_ctx_stack.pop()169 _cv_req.reset(token)170171 resp = app.response_class()172 if not session_interface.is_null_session(sess):173 session_interface.save_session(app, sess, resp)
114 unmodified lines
modified:tests/conftest.py+10 added-9 removed
4 unmodified lines
56import pytest7from _pytest import monkeypatch89import flask10from flask import Flask as _Flask9from flask import Flask10from flask.globals import request_ctx111213@pytest.fixture(scope="session", autouse=True)14def _standard_os_environ():
28 unmodified lines
43 """44 monkeypatch._setitem.extend(_standard_os_environ)454647class Flask(_Flask):48 testing = True49 secret_key = "test key"505147@pytest.fixture48def app():49 app = Flask("flask_test", root_path=os.path.dirname(__file__))50 app.config.update(51 TESTING=True,52 SECRET_KEY="test key",53 )54 return app555657@pytest.fixture
32 unmodified lines
9091 # make sure we're not leaking a request context since we are92 # testing flask internally in debug mode in a few cases93 leaks = []95 while flask._request_ctx_stack.top is not None:96 leaks.append(flask._request_ctx_stack.pop())94 while request_ctx:95 leaks.append(request_ctx._get_current_object())96 request_ctx.pop()9798 assert leaks == []99100101@pytest.fixture(params=(True, False))
98 unmodified lines
modified:tests/test_appctx.py+10 added-8 removed
1import pytest23import flask4from flask.globals import app_ctx5from flask.globals import request_ctx678def test_basic_url_generation(app):9 app.config["SERVER_NAME"] = "localhost"
20 unmodified lines
303132def test_request_context_means_app_context(app):33 with app.test_request_context():32 assert flask.current_app._get_current_object() == app33 assert flask._app_ctx_stack.top is None34 assert flask.current_app._get_current_object() is app35 assert not flask.current_app363738def test_app_context_provides_current_app(app):39 with app.app_context():38 assert flask.current_app._get_current_object() == app39 assert flask._app_ctx_stack.top is None40 assert flask.current_app._get_current_object() is app41 assert not flask.current_app424344def test_app_tearing_down(app):45 cleanup_stuff = []
130 unmodified lines
176 called.append("app")177178 @app.route("/")179 def index():178 with flask._app_ctx_stack.top:179 with flask._request_ctx_stack.top:180 with app_ctx:181 with request_ctx:182 pass181 env = flask._request_ctx_stack.top.request.environ182 assert env["werkzeug.request"] is not None183184 assert flask.request.environ["werkzeug.request"] is not None185 return ""186187 res = client.get("/")188 assert res.status_code == 200
24 unmodified lines
modified:tests/test_basic.py+17 added-29 removed
1108 unmodified lines
1109 @app.route("/fail", methods=["POST"])1110 def index():1111 return flask.request.files["foo"].filename11121113 # with statement is important because we leave an exception on the1114 # stack otherwise and we want to ensure that this is not the case1115 # to not negatively affect other tests.1116 with client:1117 with pytest.raises(DebugFilesKeyError) as e:1118 client.post("/fail", data={"foo": "index.txt"})1119 assert "no file contents were transmitted" in str(e.value)1120 assert "This was submitted: 'index.txt'" in str(e.value)1113 with pytest.raises(DebugFilesKeyError) as e:1114 client.post("/fail", data={"foo": "index.txt"})1115 assert "no file contents were transmitted" in str(e.value)1116 assert "This was submitted: 'index.txt'" in str(e.value)111711181119def test_response_types(app, client):1120 @app.route("/text")
422 unmodified lines
1543 rv = client.get("/", "http://foo.dev.local")1544 assert rv.data == b"subdomain"154515461551@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1552@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1553def test_exception_propagation(app, client):1554 def apprunner(config_key):1555 @app.route("/")1556 def index():1557 1 // 01547@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1548def test_exception_propagation(app, client, key):1549 app.testing = False15501559 if config_key is not None:1560 app.config[config_key] = True1561 with pytest.raises(Exception):1562 client.get("/")1563 else:1564 assert client.get("/").status_code == 5001551 @app.route("/")1552 def index():1553 1 // 015541566 # we have to run this test in an isolated thread because if the1567 # debug flag is set to true and an exception happens the context is1568 # not torn down. This causes other tests that run after this fail1569 # when they expect no exception on the stack.1570 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1571 t = Thread(target=apprunner, args=(config_key,))1572 t.start()1573 t.join()1555 if key is not None:1556 app.config[key] = True15571558 with pytest.raises(ZeroDivisionError):1559 client.get("/")1560 else:1561 assert client.get("/").status_code == 500156215631564@pytest.mark.parametrize("debug", [True, False])1565@pytest.mark.parametrize("use_debugger", [True, False])1566@pytest.mark.parametrize("use_reloader", [True, False])1567@pytest.mark.parametrize("propagate_exceptions", [None, True, False])
402 unmodified lines
modified:tests/test_reqctx.py+3 added-2 removed
1 unmodified line
23import pytest45import flask6from flask.globals import request_ctx7from flask.sessions import SecureCookieSessionInterface8from flask.sessions import SessionInterface910try:
105 unmodified lines
116 with app.test_request_context("/?name=World"):117 assert index() == "Hello World!"118 with app.test_request_context("/meh"):119 assert meh() == "http://localhost/meh"119 assert flask._request_ctx_stack.top is None120 assert not flask.request121122123def test_context_test(app):124 assert not flask.request
27 unmodified lines
152153 @app.route("/")154 def index():155 flask.session["fizz"] = "buzz"155 reqctx = flask._request_ctx_stack.top.copy()156 reqctx = request_ctx.copy()157158 def g():159 assert not flask.request160 assert not flask.current_app
166 unmodified lines
modified:tests/test_session_interface.py+2 added-1 removed
1import flask2from flask.globals import request_ctx3from flask.sessions import SessionInterface456def test_open_session_with_endpoint():
6 unmodified lines
13 def save_session(self, app, session, response):14 pass1516 def open_session(self, app, request):16 flask._request_ctx_stack.top.match_request()17 request_ctx.match_request()18 assert request.endpoint is not None1920 app = flask.Flask(__name__)21 app.session_interface = MySessionInterface()
7 unmodified lines
modified:tests/test_testing.py+2 added-1 removed
3 unmodified lines
45import flask6from flask import appcontext_popped7from flask.cli import ScriptInfo8from flask.globals import _cv_req9from flask.json import jsonify10from flask.testing import EnvironBuilder11from flask.testing import FlaskCliRunner12
386 unmodified lines
399400 # close the response, releasing the context held by stream_with_context401 rv.close()402 # only req_ctx fixture should still be pushed402 assert flask._request_ctx_stack.top is req_ctx403 assert _cv_req.get(None) is req_ctx
modified:CHANGES.rst+9 added
13 unmodified lines
14 ``send_from_directory``.15 - The ``RequestContext.g`` property returning ``AppContext.g`` is16 removed.1718- The app and request contexts are managed using Python context vars19 directly rather than Werkzeug's ``LocalStack``. This should result20 in better performance and memory use. :pr:`4672`2122 - Extension maintainers, be aware that ``_app_ctx_stack.top``23 and ``_request_ctx_stack.top`` are deprecated. Store data on24 ``g`` instead using a unique prefix, like25 ``g._extension_name_attr``.2627- Add new customization points to the ``Flask`` app object for many28 previously global behaviors.2930 - ``flask.url_for`` will call ``app.url_for``. :issue:`4568`
1343 unmodified lines
modified:setup.py+1 added-1 removed
2 unmodified lines
3# Metadata goes in setup.cfg. These are here for GitHub's dependency graph.4setup(5 name="Flask",6 install_requires=[7 "Werkzeug >= 2.0",7 "Werkzeug >= 2.2.0a1",8 "Jinja2 >= 3.0",9 "itsdangerous >= 2.0",10 "click >= 8.0",11 "importlib-metadata >= 3.6.0; python_version < '3.10'",
6 unmodified lines