Skip to content

Commit

Permalink
Add vary cookie for accessed session as per flask
Browse files Browse the repository at this point in the history
  • Loading branch information
Lxstr committed Mar 16, 2024
1 parent 56937a0 commit 7ab6980
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/hello.py
Expand Up @@ -29,5 +29,10 @@ def delete():
return "deleted"


@app.route("/")
def hello():
return "hello world"


if __name__ == "__main__":
app.run(debug=True)
27 changes: 27 additions & 0 deletions src/flask_session/base.py
Expand Up @@ -38,6 +38,13 @@ class ServerSideSession(CallbackDict, SessionMixin):
dict) then this must be set to ``True`` manually when modifying that data. The
session cookie will only be written to the response if this is ``True``.
.. attribute:: accessed
When data is read (or attempted read) or written, this is set to ``True``. Used by
:class:`.ServerSideSessionInterface` to add a ``Vary: Cookie``
header, which allows caching proxies to cache different pages for
different users.
Default is ``False``.
.. attribute:: permanent
Expand All @@ -59,12 +66,26 @@ def __init__(
):
def on_update(self) -> None:
self.modified = True
self.accessed = True

CallbackDict.__init__(self, initial, on_update)
self.sid = sid
if permanent:
self.permanent = permanent
self.modified = False
self.accessed = False

def __getitem__(self, key: str) -> Any:
self.accessed = True
return super().__getitem__(key)

def get(self, key: str, default: Any = None) -> Any:
self.accessed = True
return super().get(key, default)

def setdefault(self, key: str, default: Any = None) -> Any:
self.accessed = True
return super().setdefault(key, default)

def clear(self) -> None:
"""Clear the session except for the '_permanent' key."""
Expand Down Expand Up @@ -262,6 +283,12 @@ def save_session(
# Generate a prefixed session id
store_id = self._get_store_id(session.sid)

# Add a "Vary: Cookie" header if the session was accessed at all.
# This assumes the app is checking the session values in a request that
# behaves differently based on those values. ie. session.get("is_authenticated")
if session.accessed:
response.vary.add("Cookie")

# If the session is empty, do not save it to the database or set a cookie
if not session:
# If the session was deleted (empty and modified), delete the saved session from the database and tell the client to delete the cookie
Expand Down

0 comments on commit 7ab6980

Please sign in to comment.