Skip to content
Myr

contexts no longer use LocalStack

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

authored by David Lord · committed by David Lord · parent 0b2f809 · Browse files · 5 files+146 added−71 removed
This commit

State

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

Diff stats

5 files+146 added−71 removed

  • other:+146 added−71 removed

5 files+146 added−71 removed

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/ctx.py+33 added-48 removed
1import contextvars2import sys3import typing as t4from functools import update_wrapper5from types import TracebackType
1 unmodified line
7from werkzeug.exceptions import HTTPException89from . import typing as ft10from .globals import _app_ctx_stack11from .globals import _cv_app12from .globals import _cv_req13from .globals import _request_ctx_stack14from .signals import appcontext_popped15from .signals import appcontext_pushed16
197 unmodified lines
214 self.remote_addr = remote_addr215216 .. versionadded:: 0.7217 """215 return _request_ctx_stack.top is not None218 return _cv_app.get(None) is not None219220221def has_app_context() -> bool:222 """Works like :func:`has_request_context` but for the application
1 unmodified line
224 :data:`current_app` object instead.225226 .. versionadded:: 0.9227 """225 return _app_ctx_stack.top is not None228 return _cv_req.get(None) is not None229230231class AppContext:232 """The application context binds an application object implicitly
7 unmodified lines
240 def __init__(self, app: "Flask") -> None:241 self.app = app242 self.url_adapter = app.create_url_adapter(None)243 self.g = app.app_ctx_globals_class()244 self._cv_tokens: t.List[contextvars.Token] = []245242 # Like request context, app contexts can be pushed multiple times243 # but there a basic "refcount" is enough to track them.244 self._refcnt = 0245246 def push(self) -> None:247 """Binds the app context to the current context."""248 self._refcnt += 1249 _app_ctx_stack.push(self)248 self._cv_tokens.append(_cv_app.set(self))249 appcontext_pushed.send(self.app)250251 def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore252 """Pops the app context."""253 try:255 self._refcnt -= 1256 if self._refcnt <= 0:254 if len(self._cv_tokens) == 1:255 if exc is _sentinel:256 exc = sys.exc_info()[1]257 self.app.do_teardown_appcontext(exc)258 finally:261 rv = _app_ctx_stack.pop()262 assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"259 ctx = _cv_app.get()260 _cv_app.reset(self._cv_tokens.pop())261262 if ctx is not self:263 raise AssertionError(264 f"Popped wrong app context. ({ctx!r} instead of {self!r})"265 )266267 appcontext_popped.send(self.app)268269 def __enter__(self) -> "AppContext":270 self.push()
47 unmodified lines
318 except HTTPException as e:319 self.request.routing_exception = e320 self.flashes = None321 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"]] = []324322 # Functions that should be executed after the request on the response323 # object. These will be called before the regular "after_request"324 # functions.325 self._after_request_functions: t.List[ft.AfterRequestCallable] = []326327 self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []328329 def copy(self) -> "RequestContext":330 """Creates a copy of this request context with the same request object.331 This can be used to move a request context to a different greenlet.332 Because the actual request object is the same this cannot be used to
25 unmodified lines
358359 def push(self) -> None:360 # Before we push the request context we have to ensure that there361 # is an application context.363 app_ctx = _app_ctx_stack.top364 if app_ctx is None or app_ctx.app != self.app:362 app_ctx = _cv_app.get(None)363364 if app_ctx is None or app_ctx.app is not self.app:365 app_ctx = self.app.app_context()366 app_ctx.push()367 self._implicit_app_ctx_stack.append(app_ctx)367 else:369 self._implicit_app_ctx_stack.append(None)368 app_ctx = None369371 _request_ctx_stack.push(self)370 self._cv_tokens.append((_cv_req.set(self), app_ctx))371372 # Open the session at the moment that the request context is available.373 # This allows a custom open_session method to use the request context.374 # Only open a new session if this is the first time the request was
17 unmodified lines
392393 .. versionchanged:: 0.9394 Added the `exc` argument.395 """397 app_ctx = self._implicit_app_ctx_stack.pop()398 clear_request = False396 clear_request = len(self._cv_tokens) == 1397398 try:401 if not self._implicit_app_ctx_stack:399 if clear_request:400 if exc is _sentinel:401 exc = sys.exc_info()[1]402 self.app.do_teardown_request(exc)403404 request_close = getattr(self.request, "close", None)405 if request_close is not None:406 request_close()409 clear_request = True407 finally:411 rv = _request_ctx_stack.pop()408 ctx = _cv_req.get()409 token, app_ctx = self._cv_tokens.pop()410 _cv_req.reset(token)411412 # get rid of circular dependencies at the end of the request413 # so that we don't require the GC to be active.414 if clear_request:416 rv.request.environ["werkzeug.request"] = None415 ctx.request.environ["werkzeug.request"] = None416418 # Get rid of the app as well if necessary.417 if app_ctx is not None:418 app_ctx.pop(exc)419422 assert (423 rv is self424 ), f"Popped wrong request context. ({rv!r} instead of {self!r})"420 if ctx is not self:421 raise AssertionError(422 f"Popped wrong request context. ({ctx!r} instead of {self!r})"423 )424426 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)439425 def __enter__(self) -> "RequestContext":426 self.push()427 return self428
13 unmodified lines
modified:src/flask/globals.py+74 added-17 removed
1import typing as t2from contextvars import ContextVar34from werkzeug.local import LocalStack4from werkzeug.local import LocalProxy56if t.TYPE_CHECKING: # pragma: no cover7 from .app import Flask8 from .ctx import _AppCtxGlobals
1 unmodified line
10 from .ctx import RequestContext11 from .sessions import SessionMixin12 from .wrappers import Request131415class _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 needed51the current application. To solve this, set up an application context52with app.app_context(). See the documentation for more information.\53"""21_cv_app: ContextVar[t.List["AppContext"]] = ContextVar("flask.app_ctx")22_app_ctx_stack: LocalStack["AppContext"] = LocalStack(_cv_app)23app_ctx: "AppContext" = _app_ctx_stack( # type: ignore[assignment]24 unbound_message=_no_app_msg54_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)26current_app: "Flask" = _app_ctx_stack( # type: ignore[assignment]27 "app", unbound_message=_no_app_msg59current_app: "Flask" = LocalProxy( # type: ignore[assignment]60 _cv_app, "app", unbound_message=_no_app_msg61)29g: "_AppCtxGlobals" = _app_ctx_stack( # type: ignore[assignment]30 "g", unbound_message=_no_app_msg62g: "_AppCtxGlobals" = LocalProxy( # type: ignore[assignment]63 _cv_app, "g", unbound_message=_no_app_msg64)6566_no_req_msg = """\67Working outside of request context.
1 unmodified line
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"""40_cv_req: ContextVar[t.List["RequestContext"]] = ContextVar("flask.request_ctx")41_request_ctx_stack: LocalStack["RequestContext"] = LocalStack(_cv_req)42request_ctx: "RequestContext" = _request_ctx_stack( # type: ignore[assignment]43 unbound_message=_no_req_msg73_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)45request: "Request" = _request_ctx_stack( # type: ignore[assignment]46 "request", unbound_message=_no_req_msg78request: "Request" = LocalProxy( # type: ignore[assignment]79 _cv_req, "request", unbound_message=_no_req_msg80)48session: "SessionMixin" = _request_ctx_stack( # type: ignore[assignment]49 "session", unbound_message=_no_req_msg81session: "SessionMixin" = LocalProxy( # type: ignore[assignment]82 _cv_req, "session", unbound_message=_no_req_msg83)848586def __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_stack9697 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_stack106107 raise AttributeError(name)
modified:src/flask/testing.py+4 added-4 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
127 unmodified lines
146 )147 app = self.application148 environ_overrides = kwargs.setdefault("environ_overrides", {})149 self.cookie_jar.inject_wsgi(environ_overrides)150 outer_reqctx = _request_ctx_stack.top150 outer_reqctx = _cv_req.get(None)151 with app.test_request_context(*args, **kwargs) as c:152 session_interface = app.session_interface153 sess = session_interface.open_session(app, c.request)154 if sess is None:
7 unmodified lines
162 # (or None) on top of this and popping it we get exactly that163 # behavior. It's important to not use the push and pop164 # methods of the actual request context object since that would165 # mean that cleanup handlers are called166 _request_ctx_stack.push(outer_reqctx)166 token = _cv_req.set(outer_reqctx)167 try:168 yield sess169 finally:170 _request_ctx_stack.pop()170 _cv_req.reset(token)171172 resp = app.response_class()173 if not session_interface.is_null_session(sess):174 session_interface.save_session(app, sess, resp)
114 unmodified lines
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