Skip to content
Myr

Merge commit from fork

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

request context tracks session access

authored by David Lord · committed by GitHub · parents 27be933, c17f379 · 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

6 files+73 added−52 removed

modified:src/flask/app.py+2 added-2 removed
1316 unmodified lines
1317 if name in self.after_request_funcs:1318 for func in reversed(self.after_request_funcs[name]):1319 response = self.ensure_sync(func)(response)13201321 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)13231324 return response13251326 def do_teardown_request(
210 unmodified lines
modified:src/flask/ctx.py+16 added-6 removed
322 unmodified lines
323 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 lines
350 return self.__class__(351 self.app,352 environ=self.request.environ,353 request=self.request,354 session=self.session,354 session=self._session,355 )356357 def match_request(self) -> None:358 """Can be overridden by a subclass to hook into the matching
4 unmodified lines
363 self.request.url_rule, self.request.view_args = result # type: ignore364 except HTTPException as e:365 self.request.routing_exception = e366367 @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._session376377 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 lines
390 # 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)397388 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)400401 # 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 lines
modified:src/flask/sessions.py+10 added-24 removed
41 unmodified lines
42 #: this when that happens. The mixin default is hard coded to43 #: ``True``.44 modified = True4546 #: 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``.5152 .. versionchanged:: 3.1.353 This is tracked by the request context.54 """555657class SecureCookieSession(CallbackDict[str, t.Any], SessionMixin):58 """Base class for sessions based on signed cookies.5960 This session backend will set the :attr:`modified` and
8 unmodified lines
69 #: ``True`` manually when modifying that data. The session cookie70 #: will only be written to the response if this is ``True``.71 modified = False7268 #: 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 = False7373 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 = True7980 super().__init__(initial, on_update)8184 def __getitem__(self, key: str) -> t.Any:85 self.accessed = True86 return super().__getitem__(key)8288 def get(self, key: str, default: t.Any = None) -> t.Any:89 self.accessed = True90 return super().get(key, default)9192 def setdefault(self, key: str, default: t.Any = None) -> t.Any:93 self.accessed = True94 return super().setdefault(key, default)959683class 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 lines
modified:src/flask/templating.py+4 added-3 removed
20 unmodified lines
21 from .sansio.scaffold import Scaffold222324def _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 rv383940class Environment(BaseEnvironment):
180 unmodified lines
modified:tests/test_basic.py+38 added-17 removed
18 unmodified lines
19from werkzeug.routing import BuildError20from werkzeug.routing import RequestRedirect2122import flask23from flask.globals import request_ctx24from flask.testing import FlaskClient2526require_cpython_gc = pytest.mark.skipif(27 python_implementation() != "CPython",28 reason="Requires CPython GC behavior",
203 unmodified lines
232 assert client.get("/foo/").data == b"index"233 assert client.get("/foo/bar").data == b"bar"234235234def test_session(app, client):235 @app.route("/set", methods=["POST"])236 def set():237 assert not flask.session.accessed238 assert not flask.session.modified236def 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"241244 @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")245253 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 ""249250 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.modified255256 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.modified262263 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.modified269270 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.modified276277278def test_session_path(app, client):279 app.config.update(APPLICATION_ROOT="/foo")280281 @app.route("/")
1684 unmodified lines
modified:CHANGES.rst+3 added
1 unmodified line
2-------------34Unreleased56- 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`8910Version 3.1.211-------------1213Released 2025-08-19
1620 unmodified lines