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
Provenance
- Commit
cbebdae- Tree
57e3f2f- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
c757882- Parent 2
e0dad45
23 files changed+344 added−345 removed
modified:docs/patterns/sqlite3.rst-4 removed
28 unmodified lines29 or create an application context itself. At that point the ``get_db``30 function can be used to get the current database connection. Whenever the31 context is destroyed the database connection will be terminated.32 33-Note: 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`35-object was bound to the request and not application context.36-33 Example::34 35 @app.route('/')36 def index():111 unmodified linesmodified:docs/api.rst+14 added-42 removed
309 unmodified lines310 311 .. autoclass:: flask.ctx.RequestContext312 :members:313 314-.. data:: _request_ctx_stack314+.. data:: flask.globals.request_ctx315 316- 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``.319 322- 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.323 325- `app`326- the active Flask application.327-328- `url_adapter`329- the URL adapter that was used to match the request.330-331- `request`332- the current request object.333-334- `session`335- the active session object.336-337- `g`338- an object with all the attributes of the :data:`flask.g` object.339-340- `flashes`341- an internal cache for the flashed messages.342-343- Example usage::344-345- from flask import _request_ctx_stack346-347- def get_session():348- ctx = _request_ctx_stack.top349- if ctx is not None:350- return ctx.session351-324 .. autoclass:: flask.ctx.AppContext325 :members:326 355-.. data:: _app_ctx_stack327+.. data:: flask.globals.app_ctx328 357- 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``.332 363- .. 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.336 337 .. autoclass:: flask.blueprints.BlueprintSetupState338 :members:339 410 unmodified linesmodified:docs/appcontext.rst-8 removed
134 unmodified lines135 136 Accessing ``db`` will call ``get_db`` internally, in the same way that137 :data:`current_app` works.138 139-----139 141-If you're writing an extension, :data:`g` should be reserved for user142-code. You may store internal data on the context itself, but be sure to143-use a sufficiently unique name. The current context is accessed with144-:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see145-:doc:`/extensiondev`.146-147-140 Events and Signals141 ------------------142 143 The application will call functions registered with6 unmodified linesmodified:docs/extensiondev.rst-6 removed
185 unmodified lines186 when the application context ends. If it should only be valid during a187 request, or would not be used in the CLI outside a reqeust, use188 :meth:`~flask.Flask.teardown_request`.189 190-An older technique for storing context data was to store it on191-``_app_ctx_stack.top`` or ``_request_ctx_stack.top``. However, this just192-moves the same namespace collision problem elsewhere (although less193-likely) and modifies objects that are very internal to Flask's194-operations. Prefer storing data under a unique name in ``g``.190 196-191 Views and Models192 ----------------193 194 Your extension views might want to interact with specific models in your110 unmodified linesmodified:docs/reqcontext.rst+13 added-12 removed
35 unmodified lines36 context, which also pushes an :doc:`app context </appcontext>`. When the37 request ends it pops the request context then the application context.38 39 The context is unique to each thread (or other worker type).40-:data:`request` cannot be passed to another thread, the other thread41-will have a different context stack and will not know about the request42-the parent thread was pointing to.40+:data:`request` cannot be passed to another thread, the other thread has41+a different context space and will not know about the request the parent42+thread was pointing to.43 44-Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`45-for more information on how this works internally.44+Context locals are implemented using Python's :mod:`contextvars` and45+Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46+lifetime of context vars automatically, and local proxy wraps that47+low-level interface to make the data easier to work with.48 49 50 Manually Push a Context51 -----------------------36 unmodified lines88 ---------------------89 90 The :meth:`Flask.wsgi_app` method is called to handle each request. It91 manages the contexts during the request. Internally, the request and90-application contexts work as stacks, :data:`_request_ctx_stack` and91-:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the92+application contexts work like stacks. When contexts are pushed, the93 proxies that depend on them are available and point at information from93-the top context on the stack.94+the top item.95 96 When the request starts, a :class:`~ctx.RequestContext` is created and97 pushed, which creates and pushes an :class:`~ctx.AppContext` first if98 a context for that application is not already the top context. While99 these contexts are pushed, the :data:`current_app`, :data:`g`,100 :data:`request`, and :data:`session` proxies are available to the101 original thread handling the request.102 102-Because the contexts are stacks, other contexts may be pushed to change103-the proxies during a request. While this is not a common pattern, it104-can be used in advanced applications to, for example, do internal105-redirects or chain different applications together.103+Other contexts may be pushed to change the proxies during a request.104+While this is not a common pattern, it can be used in advanced105+applications to, for example, do internal redirects or chain different106+applications together.107 108 After the request is dispatched and a response is generated and sent,109 the request context is popped, which then pops the application context.110 Immediately before they are popped, the :meth:`~Flask.teardown_request`137 unmodified linesmodified:src/flask/__init__.py+26 added-2 removed
9 unmodified lines10 from .ctx import after_this_request as after_this_request11 from .ctx import copy_current_request_context as copy_current_request_context12 from .ctx import has_app_context as has_app_context13 from .ctx import has_request_context as has_request_context14-from .globals import _app_ctx_stack as _app_ctx_stack15-from .globals import _request_ctx_stack as _request_ctx_stack14 from .globals import current_app as current_app15 from .globals import g as g16 from .globals import request as request17 from .globals import session as session24 unmodified lines42 from .templating import stream_template as stream_template43 from .templating import stream_template_string as stream_template_string44 45 __version__ = "2.2.0.dev0"46+47+48+def __getattr__(name):49+ if name == "_app_ctx_stack":50+ import warnings51+ from .globals import __app_ctx_stack52+53+ 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_stack59+60+ if name == "_request_ctx_stack":61+ import warnings62+ from .globals import __request_ctx_stack63+64+ 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_stack70+71+ raise AttributeError(name)modified:src/flask/app.py+34 added-31 removed
36 unmodified lines37 from .config import ConfigAttribute38 from .ctx import _AppCtxGlobals39 from .ctx import AppContext40 from .ctx import RequestContext41-from .globals import _app_ctx_stack42-from .globals import _request_ctx_stack41+from .globals import _cv_app42+from .globals import _cv_req43 from .globals import g44 from .globals import request45+from .globals import request_ctx46 from .globals import session47 from .helpers import _split_blueprint_path48 from .helpers import get_debug_flag49 from .helpers import get_env1233 unmodified lines1283 return f1284 1285 @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.1291 1290- Example::1292+ .. code-block:: python1293 1292- ctx = app.app_context()1293- ctx.push()1294- ...1295- ctx.pop()1294+ with app.app_context():1295+ ...1296 1297- 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.1302 1302- 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.1307 1305- 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.1311 1312 The return values of teardown functions are ignored.1313 1314 .. versionadded:: 0.9240 unmodified lines1555 .. 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)1573 1574 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 and56 unmodified lines1633 behavior of ``OPTIONS`` responses.1634 1635 .. 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 lines1742 1743 .. 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)1747 1748 if req_ctx is not None:1749 url_adapter = req_ctx.url_adapter1750 blueprint_name = req_ctx.request.blueprint10 unmodified lines1761 # 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)1766 1767 # 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 lines1792 1793 self.inject_url_defaults(endpoint, values)1794 1795 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 lines2101 :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]2106 2107 for func in ctx._after_request_functions:2108 response = self.ensure_sync(func)(response)2109 197 unmodified lines2307 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())2313 2314 if error is not None and self.should_ignore_error(error):2315 error = None2316 8 unmodified linesmodified:src/flask/cli.py+3 added-5 removed
1049 unmodified lines1050 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_stack1054 1056- 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 = {}1061 1062 # Support the regular Python interpreter startup script if someone2 unmodified lines1065 if startup and os.path.isfile(startup):1066 with open(startup) as f:1067 eval(compile(f.read(), startup, "exec"), ctx)1068 1071- ctx.update(app.make_shell_context())1069+ ctx.update(current_app.make_shell_context())1070 1071 # 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 linesmodified:src/flask/ctx.py+60 added-79 removed
1+import contextvars2 import sys3 import typing as t4 from functools import update_wrapper5 from types import TracebackType6 7 from werkzeug.exceptions import HTTPException8 9 from . import typing as ft9-from .globals import _app_ctx_stack10-from .globals import _request_ctx_stack10+from .globals import _cv_app11+from .globals import _cv_req12 from .signals import appcontext_popped13 from .signals import appcontext_pushed14 15 if t.TYPE_CHECKING: # pragma: no cover87 unmodified lines103 def __iter__(self) -> t.Iterator[str]:104 return iter(self.__dict__)105 106 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)111 112 113 def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:16 unmodified lines130 some headers without converting the return value into a response object.131 132 .. versionadded:: 0.9133 """133- top = _request_ctx_stack.top134+ ctx = _cv_req.get(None)135 135- 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 )141 141- top._after_request_functions.append(f)142+ ctx._after_request_functions.append(f)143 return f144 145 146 def copy_current_request_context(f: t.Callable) -> t.Callable:19 unmodified lines166 return 'Regular response'167 168 .. versionadded:: 0.10169 """169- top = _request_ctx_stack.top170+ ctx = _cv_req.get(None)171 171- 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 )177 177- reqctx = top.copy()178+ ctx = ctx.copy()179 180 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)183 184 return update_wrapper(wrapper, f)185 186 25 unmodified lines212 self.remote_addr = remote_addr213 214 .. versionadded:: 0.7215 """215- return _request_ctx_stack.top is not None216+ return _cv_app.get(None) is not None217 218 219 def has_app_context() -> bool:220 """Works like :func:`has_request_context` but for the application1 unmodified line222 :data:`current_app` object instead.223 224 .. versionadded:: 0.9225 """225- return _app_ctx_stack.top is not None226+ return _cv_req.get(None) is not None227 228 229 class 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 """235 236 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] = []241 242- # Like request context, app contexts can be pushed multiple times243- # but there a basic "refcount" is enough to track them.244- self._refcnt = 0245-242 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)246 247 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())257+258+ if ctx is not self:259+ raise AssertionError(260+ f"Popped wrong app context. ({ctx!r} instead of {self!r})"261+ )262+263 appcontext_popped.send(self.app)264 265 def __enter__(self) -> "AppContext":266 self.push()8 unmodified lines275 self.pop(exc_value)276 277 278 class 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.283 284 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 lines306 ) -> 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 = session318-319- # 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"]] = []324-316+ 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] = []322 323+ self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []324+325 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 to25 unmodified lines354 355 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)359+360+ 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 = None365 371- _request_ctx_stack.push(self)366+ self._cv_tokens.append((_cv_req.set(self), app_ctx))367 368 # 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 was17 unmodified lines388 389 .. 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) == 1393 394 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)399 400 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)407 408 # 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"] = None412 418- # Get rid of the app as well if necessary.413 if app_ctx is not None:414 app_ctx.pop(exc)415 422- 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+ )420 426- def auto_pop(self, exc: t.Optional[BaseException]) -> None:427- """428- .. deprecated:: 2.2429- Will be removed in Flask 2.3.430- """431- import warnings432-433- 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)439-421 def __enter__(self) -> "RequestContext":422 self.push()423 return self424 13 unmodified linesmodified:src/flask/debughelpers.py+3 added-4 removed
1 import typing as t2 3 from .app import Flask4 from .blueprints import Blueprint5-from .globals import _request_ctx_stack5+from .globals import request_ctx6 7 8 class UnexpectedUnicodeError(AssertionError, UnicodeError):9 """Raised in places where we want some better error reporting for105 unmodified lines115 """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.blueprint121 122 for idx, (loader, srcobj, triple) in enumerate(attempts):123 if isinstance(srcobj, Flask):124 src_info = f"application {srcobj.import_name!r}"34 unmodified linesmodified:src/flask/globals.py+84 added-36 removed
1 import typing as t2-from functools import partial2+from contextvars import ContextVar3 4 from werkzeug.local import LocalProxy5-from werkzeug.local import LocalStack5 6 if 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 Request13 13-_request_ctx_err_msg = """\14-Working outside of request context.14 16-This typically means that you attempted to use functionality that needed17-an active HTTP request. Consult the documentation on testing for18-information about how to avoid this problem.\19-"""20-_app_ctx_err_msg = """\15+class _FakeStack:16+ def __init__(self, name: str, cv: ContextVar[t.Any]) -> None:17+ self.name = name18+ self.cv = cv19+20+ def _warn(self):21+ import warnings22+23+ 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+ )30+31+ def push(self, obj: t.Any) -> None:32+ self._warn()33+ self.cv.set(obj)34+35+ def pop(self) -> t.Any:36+ self._warn()37+ ctx = self.cv.get(None)38+ self.cv.set(None)39+ return ctx40+41+ @property42+ def top(self) -> t.Optional[t.Any]:43+ self._warn()44+ return self.cv.get(None)45+46+47+_no_app_msg = """\48 Working outside of application context.49 50 This typically means that you attempted to use functionality that needed24-to interface with the current application object in some way. To solve25-this, set up an application context with app.app_context(). See the26-documentation for more information.\51+the current application. To solve this, set up an application context52+with 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)56+app_ctx: "AppContext" = LocalProxy( # type: ignore[assignment]57+ _cv_app, unbound_message=_no_app_msg58+)59+current_app: "Flask" = LocalProxy( # type: ignore[assignment]60+ _cv_app, "app", unbound_message=_no_app_msg61+)62+g: "_AppCtxGlobals" = LocalProxy( # type: ignore[assignment]63+ _cv_app, "g", unbound_message=_no_app_msg64+)65 66+_no_req_msg = """\67+Working outside of request context.68 30-def _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)69+This typically means that you attempted to use functionality that needed70+an active HTTP request. Consult the documentation on testing for71+information about how to avoid this problem.\72+"""73+_cv_req: ContextVar["RequestContext"] = ContextVar("flask.request_ctx")74+__request_ctx_stack = _FakeStack("request", _cv_req)75+request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment]76+ _cv_req, unbound_message=_no_req_msg77+)78+request: "Request" = LocalProxy( # type: ignore[assignment]79+ _cv_req, "request", unbound_message=_no_req_msg80+)81+session: "SessionMixin" = LocalProxy( # type: ignore[assignment]82+ _cv_req, "session", unbound_message=_no_req_msg83+)84 85 37-def _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)86+def __getattr__(name: str) -> t.Any:87+ if name == "_app_ctx_stack":88+ import warnings89 90+ 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_stack96 44-def _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 warnings99 100+ 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_stack106 51-# context locals52-_request_ctx_stack = LocalStack()53-_app_ctx_stack = LocalStack()54-current_app: "Flask" = LocalProxy(_find_app) # type: ignore55-request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore56-session: "SessionMixin" = LocalProxy( # type: ignore57- partial(_lookup_req_object, "session")58-)59-g: "_AppCtxGlobals" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore107+ raise AttributeError(name)modified:src/flask/helpers.py+8 added-8 removed
10 unmodified lines11 import werkzeug.utils12 from werkzeug.exceptions import abort as _wz_abort13 from werkzeug.utils import redirect as _wz_redirect14 15-from .globals import _request_ctx_stack15+from .globals import _cv_req16 from .globals import current_app17 from .globals import request18+from .globals import request_ctx19 from .globals import session20 from .signals import message_flashed21 22 if t.TYPE_CHECKING: # pragma: no cover87 unmodified lines110 111 return update_wrapper(decorator, generator_or_function) # type: ignore112 113 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 lines377 :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 linesmodified:src/flask/scaffold.py+16 added-19 removed
572 unmodified lines573 return f574 575 @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.580 582- Example::581+ .. code-block:: python582 584- ctx = app.test_request_context()585- ctx.push()586- ...587- ctx.pop()583+ with app.test_request_context():584+ ...585 589- 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.589 594- 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.594 599- 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.598 599 The return values of teardown functions are ignored.600 """601 self.teardown_request_funcs.setdefault(None, []).append(f)288 unmodified linesmodified:src/flask/templating.py+21 added-29 removed
3 unmodified lines4 from jinja2 import Environment as BaseEnvironment5 from jinja2 import Template6 from jinja2 import TemplateNotFound7 8-from .globals import _app_ctx_stack9-from .globals import _request_ctx_stack8+from .globals import _cv_app9+from .globals import _cv_req10 from .globals import current_app11 from .globals import request12 from .helpers import stream_with_context13 from .signals import before_render_template7 unmodified lines21 def _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.request91 unmodified lines123 124 return list(result)125 126 127-def _render(template: Template, context: dict, app: "Flask") -> str:127+def _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 rv2 unmodified lines135 def 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.140 141- :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)148 149 150 def 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.153 160- :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)160 161 162 def _stream(163 app: "Flask", template: Template, context: t.Dict[str, t.Any]49 unmodified linesmodified:src/flask/testing.py+8 added-9 removed
9 unmodified lines10 from werkzeug.urls import url_parse11 from werkzeug.wrappers import Request as BaseRequest12 13 from .cli import ScriptInfo14-from .globals import _request_ctx_stack14+from .globals import _cv_req15 from .json import dumps as json_dumps16 from .sessions import SessionMixin17 18 if t.TYPE_CHECKING: # pragma: no cover74 unmodified lines93 return json_dumps(obj, **kwargs)94 95 96 class 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`.101 102 .. versionchanged:: 0.12103 `app.test_client()` includes preset default environment, which can be104 set after instantiation of the `app.test_client()` object in40 unmodified lines145 )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 lines161 # (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)170 171 resp = app.response_class()172 if not session_interface.is_null_session(sess):173 session_interface.save_session(app, sess, resp)114 unmodified linesmodified:tests/conftest.py+10 added-9 removed
4 unmodified lines5 6 import pytest7 from _pytest import monkeypatch8 9-import flask10-from flask import Flask as _Flask9+from flask import Flask10+from flask.globals import request_ctx11 12 13 @pytest.fixture(scope="session", autouse=True)14 def _standard_os_environ():28 unmodified lines43 """44 monkeypatch._setitem.extend(_standard_os_environ)45 46 47-class Flask(_Flask):48- testing = True49- secret_key = "test key"50-51-47 @pytest.fixture48 def 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 app55 56 57 @pytest.fixture32 unmodified lines90 91 # 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()97+98 assert leaks == []99 100 101 @pytest.fixture(params=(True, False))98 unmodified linesmodified:tests/test_appctx.py+10 added-8 removed
1 import pytest2 3 import flask4+from flask.globals import app_ctx5+from flask.globals import request_ctx6 7 8 def test_basic_url_generation(app):9 app.config["SERVER_NAME"] = "localhost"20 unmodified lines30 31 32 def 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_app36 37 38 def 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_app42 43 44 def test_app_tearing_down(app):45 cleanup_stuff = []130 unmodified lines176 called.append("app")177 178 @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 None183+184+ assert flask.request.environ["werkzeug.request"] is not None185 return ""186 187 res = client.get("/")188 assert res.status_code == 20024 unmodified linesmodified:tests/test_basic.py+17 added-29 removed
1108 unmodified lines1109 @app.route("/fail", methods=["POST"])1110 def index():1111 return flask.request.files["foo"].filename1112 1113- # 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)1117 1118 1119 def test_response_types(app, client):1120 @app.route("/text")422 unmodified lines1543 rv = client.get("/", "http://foo.dev.local")1544 assert rv.data == b"subdomain"1545 1546 1551-@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1552-@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1553-def 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])1548+def test_exception_propagation(app, client, key):1549+ app.testing = False1550 1559- 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 // 01554 1566- # 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] = True1557 1558+ with pytest.raises(ZeroDivisionError):1559+ client.get("/")1560+ else:1561+ assert client.get("/").status_code == 5001562 1563+1564 @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 linesmodified:tests/test_reqctx.py+3 added-2 removed
1 unmodified line2 3 import pytest4 5 import flask6+from flask.globals import request_ctx7 from flask.sessions import SecureCookieSessionInterface8 from flask.sessions import SessionInterface9 10 try:105 unmodified lines116 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.request121 122 123 def test_context_test(app):124 assert not flask.request27 unmodified lines152 153 @app.route("/")154 def index():155 flask.session["fizz"] = "buzz"155- reqctx = flask._request_ctx_stack.top.copy()156+ reqctx = request_ctx.copy()157 158 def g():159 assert not flask.request160 assert not flask.current_app166 unmodified linesmodified:tests/test_session_interface.py+2 added-1 removed
1 import flask2+from flask.globals import request_ctx3 from flask.sessions import SessionInterface4 5 6 def test_open_session_with_endpoint():6 unmodified lines13 def save_session(self, app, session, response):14 pass15 16 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 None19 20 app = flask.Flask(__name__)21 app.session_interface = MySessionInterface()7 unmodified linesmodified:tests/test_testing.py+2 added-1 removed
3 unmodified lines4 5 import flask6 from flask import appcontext_popped7 from flask.cli import ScriptInfo8+from flask.globals import _cv_req9 from flask.json import jsonify10 from flask.testing import EnvironBuilder11 from flask.testing import FlaskCliRunner12 386 unmodified lines399 400 # 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_ctxmodified:CHANGES.rst+9 added
13 unmodified lines14 ``send_from_directory``.15 - The ``RequestContext.g`` property returning ``AppContext.g`` is16 removed.17 18+- 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`21+22+ - 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``.26+27 - Add new customization points to the ``Flask`` app object for many28 previously global behaviors.29 30 - ``flask.url_for`` will call ``app.url_for``. :issue:`4568`1343 unmodified linesmodified:setup.py+1 added-1 removed
2 unmodified lines3 # Metadata goes in setup.cfg. These are here for GitHub's dependency graph.4 setup(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