1313from django.http.response import HttpResponse
1414from django.template.response import SimpleTemplateResponse
1515from django.utils.cache import (
16+ cc_delim_re,
1617 get_cache_key,
1718 get_max_age,
1819 has_vary_header,
@@ -45,6 +46,9 @@ class Status(Enum):
4546
4647
4748def _patch_header(response: HttpResponse, status: Status) -> None:
49+ """
50+ Adds our Cache Control status to the response headers.
51+ """
4852 # Patch cache-control with no-cache if it is not already set.
4953 if status == Status.SKIP and not response.get("Cache-Control", None):
5054 response["Cache-Control"] = CacheControl.NOCACHE.value
@@ -53,6 +57,31 @@ def _patch_header(response: HttpResponse, status: Status) -> None:
5357 response[wagtailcache_settings.WAGTAIL_CACHE_HEADER] = status.value
5458
5559
60+ def _delete_vary_cookie(response: HttpResponse) -> None:
61+ """
62+ Deletes the ``Vary: Cookie`` header while keeping other items of the
63+ Vary header in tact. Inspired by ``django.utils.cache.patch_vary_headers``.
64+ """
65+ if not response.has_header("Vary"):
66+ return
67+ # Parse the value of Vary header.
68+ vary_headers = cc_delim_re.split(response["Vary"])
69+ # Build a lowercase-keyed dict to preserve the original case.
70+ vhdict = {}
71+ for item in vary_headers:
72+ vhdict.update({item.lower(): item})
73+ # Delete "Cookie".
74+ if "cookie" in vhdict:
75+ del vhdict["cookie"]
76+ # Delete the header if it's now empty.
77+ if not vhdict:
78+ del response["Vary"]
79+ return
80+ # Else patch the header.
81+ vary_headers = [vhdict[k] for k in vhdict]
82+ response["Vary"] = ", ".join(vary_headers)
83+
84+
5685def _chop_querystring(r: WSGIRequest) -> WSGIRequest:
5786 """
5887 Given a request object, remove any of our ignored querystrings from it.
@@ -103,15 +132,15 @@ def _chop_response_vary(r: WSGIRequest, s: HttpResponse) -> HttpResponse:
103132 if (
104133 not s.has_header("Set-Cookie")
105134 and s.has_header("Vary")
106- and s["Vary"].lower() == "cookie"
135+ and has_vary_header(s, "Cookie")
107136 and not (
108137 settings.CSRF_COOKIE_NAME in s.cookies
109138 or settings.CSRF_COOKIE_NAME in r.COOKIES
110139 or settings.SESSION_COOKIE_NAME in s.cookies
111140 or settings.SESSION_COOKIE_NAME in r.COOKIES
112141 )
113142 ):
114- del s["Vary"]
143+ _delete_vary_cookie(s)
115144 return s
116145
117146
0 commit comments