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
Provenance
- Commit
d597db6- Tree
1b8cee1- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
0b2f809
5 files changed+146 added−71 removed
modified: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/ctx.py+33 added-48 removed
1+import contextvars2 import sys3 import typing as t4 from functools import update_wrapper5 from types import TracebackType1 unmodified line7 from werkzeug.exceptions import HTTPException8 9 from . import typing as ft10 from .globals import _app_ctx_stack11+from .globals import _cv_app12+from .globals import _cv_req13 from .globals import _request_ctx_stack14 from .signals import appcontext_popped15 from .signals import appcontext_pushed16 197 unmodified lines214 self.remote_addr = remote_addr215 216 .. versionadded:: 0.7217 """215- return _request_ctx_stack.top is not None218+ return _cv_app.get(None) is not None219 220 221 def has_app_context() -> bool:222 """Works like :func:`has_request_context` but for the application1 unmodified line224 :data:`current_app` object instead.225 226 .. versionadded:: 0.9227 """225- return _app_ctx_stack.top is not None228+ return _cv_req.get(None) is not None229 230 231 class AppContext:232 """The application context binds an application object implicitly7 unmodified lines240 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] = []245 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-246 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)250 251 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())261+262+ if ctx is not self:263+ raise AssertionError(264+ f"Popped wrong app context. ({ctx!r} instead of {self!r})"265+ )266+267 appcontext_popped.send(self.app)268 269 def __enter__(self) -> "AppContext":270 self.push()47 unmodified lines318 except HTTPException as e:319 self.request.routing_exception = e320 self.flashes = None321 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-322 # 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] = []326 327+ self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []328+329 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 to25 unmodified lines358 359 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)363+364+ 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 = None369 371- _request_ctx_stack.push(self)370+ self._cv_tokens.append((_cv_req.set(self), app_ctx))371 372 # 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 was17 unmodified lines392 393 .. 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) == 1397 398 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)403 404 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)411 412 # 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"] = None416 418- # Get rid of the app as well if necessary.417 if app_ctx is not None:418 app_ctx.pop(exc)419 422- 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+ )424 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-425 def __enter__(self) -> "RequestContext":426 self.push()427 return self428 13 unmodified linesmodified:src/flask/globals.py+74 added-17 removed
1 import typing as t2 from contextvars import ContextVar3 4-from werkzeug.local import LocalStack4+from werkzeug.local import LocalProxy5 6 if t.TYPE_CHECKING: # pragma: no cover7 from .app import Flask8 from .ctx import _AppCtxGlobals1 unmodified line10 from .ctx import RequestContext11 from .sessions import SessionMixin12 from .wrappers import Request13 14+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 needed51 the current application. To solve this, set up an application context52 with 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)23-app_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)56+app_ctx: "AppContext" = LocalProxy( # type: ignore[assignment]57+ _cv_app, unbound_message=_no_app_msg58 )26-current_app: "Flask" = _app_ctx_stack( # type: ignore[assignment]27- "app", unbound_message=_no_app_msg59+current_app: "Flask" = LocalProxy( # type: ignore[assignment]60+ _cv_app, "app", unbound_message=_no_app_msg61 )29-g: "_AppCtxGlobals" = _app_ctx_stack( # type: ignore[assignment]30- "g", unbound_message=_no_app_msg62+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.1 unmodified line69 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 """40-_cv_req: ContextVar[t.List["RequestContext"]] = ContextVar("flask.request_ctx")41-_request_ctx_stack: LocalStack["RequestContext"] = LocalStack(_cv_req)42-request_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)75+request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment]76+ _cv_req, unbound_message=_no_req_msg77 )45-request: "Request" = _request_ctx_stack( # type: ignore[assignment]46- "request", unbound_message=_no_req_msg78+request: "Request" = LocalProxy( # type: ignore[assignment]79+ _cv_req, "request", unbound_message=_no_req_msg80 )48-session: "SessionMixin" = _request_ctx_stack( # type: ignore[assignment]49- "session", unbound_message=_no_req_msg81+session: "SessionMixin" = LocalProxy( # type: ignore[assignment]82+ _cv_req, "session", unbound_message=_no_req_msg83 )84+85+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+97+ 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+107+ raise AttributeError(name)modified:src/flask/testing.py+4 added-4 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 cover127 unmodified lines146 )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 lines162 # (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)171 172 resp = app.response_class()173 if not session_interface.is_null_session(sess):174 session_interface.save_session(app, sess, resp)114 unmodified linesmodified: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 lines