request context tracks session access
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 27be933 · Browse files · 6 files·+73 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+73 added−52 removed
- tests:+38 added−17 removed
- other:+35 added−35 removed
Provenance
- Commit
c17f379- Tree
128b778- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
27be933
6 files changed+73 added−52 removed
modified:src/flask/app.py+2 added-2 removed
1316 unmodified lines1317 if name in self.after_request_funcs:1318 for func in reversed(self.after_request_funcs[name]):1319 response = self.ensure_sync(func)(response)1320 1321- if not self.session_interface.is_null_session(ctx.session):1322- self.session_interface.save_session(self, ctx.session, response)1321+ if not self.session_interface.is_null_session(ctx._session):1322+ self.session_interface.save_session(self, ctx._session, response)1323 1324 return response1325 1326 def do_teardown_request(210 unmodified linesmodified:src/flask/ctx.py+16 added-6 removed
322 unmodified lines323 self.url_adapter = app.create_url_adapter(self.request)324 except HTTPException as e:325 self.request.routing_exception = e326 self.flashes: list[tuple[str, str]] | None = None327- self.session: SessionMixin | None = session327+ self._session: SessionMixin | None = session328 # Functions that should be executed after the request on the response329 # object. These will be called before the regular "after_request"330 # functions.331 self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []18 unmodified lines350 return self.__class__(351 self.app,352 environ=self.request.environ,353 request=self.request,354- session=self.session,354+ session=self._session,355 )356 357 def match_request(self) -> None:358 """Can be overridden by a subclass to hook into the matching4 unmodified lines363 self.request.url_rule, self.request.view_args = result # type: ignore364 except HTTPException as e:365 self.request.routing_exception = e366 367+ @property368+ def session(self) -> SessionMixin:369+ """The session data associated with this request. Not available until370+ this context has been pushed. Accessing this property, also accessed by371+ the :data:`~flask.session` proxy, sets :attr:`.SessionMixin.accessed`.372+ """373+ assert self._session is not None, "The session has not yet been opened."374+ self._session.accessed = True375+ return self._session376+377 def push(self) -> None:378 # Before we push the request context we have to ensure that there379 # is an application context.380 app_ctx = _cv_app.get(None)9 unmodified lines390 # Open the session at the moment that the request context is available.391 # This allows a custom open_session method to use the request context.392 # Only open a new session if this is the first time the request was393 # pushed, otherwise stream_with_context loses the session.384- if self.session is None:394+ if self._session is None:395 session_interface = self.app.session_interface386- self.session = session_interface.open_session(self.app, self.request)396+ self._session = session_interface.open_session(self.app, self.request)397 388- if self.session is None:389- self.session = session_interface.make_null_session(self.app)398+ if self._session is None:399+ self._session = session_interface.make_null_session(self.app)400 401 # Match the request URL after loading the session, so that the402 # session is available in custom URL converters.403 if self.url_adapter is not None:56 unmodified linesmodified:src/flask/sessions.py+10 added-24 removed
41 unmodified lines42 #: this when that happens. The mixin default is hard coded to43 #: ``True``.44 modified = True45 46- #: Some implementations can detect when session data is read or47- #: written and set this when that happens. The mixin default is hard48- #: coded to ``True``.49- accessed = True46+ accessed = False47+ """Indicates if the session was accessed, even if it was not modified. This48+ is set when the session object is accessed through the request context,49+ including the global :data:`.session` proxy. A ``Vary: cookie`` header will50+ be added if this is ``True``.51 52+ .. versionchanged:: 3.1.353+ This is tracked by the request context.54+ """55 56+57 class SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):58 """Base class for sessions based on signed cookies.59 60 This session backend will set the :attr:`modified` and8 unmodified lines69 #: ``True`` manually when modifying that data. The session cookie70 #: will only be written to the response if this is ``True``.71 modified = False72 68- #: When data is read or written, this is set to ``True``. Used by69- # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``70- #: header, which allows caching proxies to cache different pages for71- #: different users.72- accessed = False73-73 def __init__(74 self,76- initial: c.Mapping[str, t.Any] | c.Iterable[tuple[str, t.Any]] | None = None,75+ initial: c.Mapping[str, t.Any] | None = None,76 ) -> None:77 def on_update(self: te.Self) -> None:78 self.modified = True80- self.accessed = True79 80 super().__init__(initial, on_update)81 84- def __getitem__(self, key: str) -> t.Any:85- self.accessed = True86- return super().__getitem__(key)82 88- def get(self, key: str, default: t.Any = None) -> t.Any:89- self.accessed = True90- return super().get(key, default)91-92- def setdefault(self, key: str, default: t.Any = None) -> t.Any:93- self.accessed = True94- return super().setdefault(key, default)95-96-83 class NullSession(SecureCookieSession):84 """Class used to generate nicer error messages if sessions are not85 available. Will still allow read-only access to the empty session86 but fail on setting.299 unmodified linesmodified:src/flask/templating.py+4 added-3 removed
20 unmodified lines21 from .sansio.scaffold import Scaffold22 23 24 def _default_template_ctx_processor() -> dict[str, t.Any]:25- """Default template context processor. Injects `request`,26- `session` and `g`.25+ """Default template context processor. Replaces the ``request`` and ``g``26+ proxies with their concrete objects for faster access.27 """28 appctx = _cv_app.get(None)29 reqctx = _cv_request.get(None)30 rv: dict[str, t.Any] = {}31 if appctx is not None:32 rv["g"] = appctx.g33 if reqctx is not None:34 rv["request"] = reqctx.request35- rv["session"] = reqctx.session35+ # The session proxy cannot be replaced, accessing it gets36+ # RequestContext.session, which sets session.accessed.37 return rv38 39 40 class Environment(BaseEnvironment):180 unmodified linesmodified:tests/test_basic.py+38 added-17 removed
18 unmodified lines19 from werkzeug.routing import BuildError20 from werkzeug.routing import RequestRedirect21 22 import flask23+from flask.globals import request_ctx24+from flask.testing import FlaskClient25 26 require_cpython_gc = pytest.mark.skipif(27 python_implementation() != "CPython",28 reason="Requires CPython GC behavior",203 unmodified lines232 assert client.get("/foo/").data == b"index"233 assert client.get("/foo/bar").data == b"bar"234 235 234-def test_session(app, client):235- @app.route("/set", methods=["POST"])236- def set():237- assert not flask.session.accessed238- assert not flask.session.modified236+def test_session_accessed(app: flask.Flask, client: FlaskClient) -> None:237+ @app.post("/")238+ def do_set():239 flask.session["value"] = flask.request.form["value"]240- assert flask.session.accessed241- assert flask.session.modified240 return "value set"241 244- @app.route("/get")245- def get():246- assert not flask.session.accessed247- assert not flask.session.modified248- v = flask.session.get("value", "None")249- assert flask.session.accessed250- assert not flask.session.modified251- return v242+ @app.get("/")243+ def do_get():244+ return flask.session.get("value", "None")245 253- assert client.post("/set", data={"value": "42"}).data == b"value set"254- assert client.get("/get").data == b"42"246+ @app.get("/nothing")247+ def do_nothing() -> str:248+ return ""249 250+ with client:251+ rv = client.get("/nothing")252+ assert "cookie" not in rv.vary253+ assert not request_ctx._session.accessed254+ assert not request_ctx._session.modified255 256+ with client:257+ rv = client.post(data={"value": "42"})258+ assert rv.text == "value set"259+ assert "cookie" in rv.vary260+ assert request_ctx._session.accessed261+ assert request_ctx._session.modified262+263+ with client:264+ rv = client.get()265+ assert rv.text == "42"266+ assert "cookie" in rv.vary267+ assert request_ctx._session.accessed268+ assert not request_ctx._session.modified269+270+ with client:271+ rv = client.get("/nothing")272+ assert rv.text == ""273+ assert "cookie" not in rv.vary274+ assert not request_ctx._session.accessed275+ assert not request_ctx._session.modified276+277+278 def test_session_path(app, client):279 app.config.update(APPLICATION_ROOT="/foo")280 281 @app.route("/")1684 unmodified linesmodified:CHANGES.rst+3 added
1 unmodified line2 -------------3 4 Unreleased5 6+- The session is marked as accessed for operations that only access the keys7+ but not the values, such as ``in`` and ``len``. :ghsa:`68rp-wp8r-4726`8 9+10 Version 3.1.211 -------------12 13 Released 2025-08-191620 unmodified lines