cache.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. """
  2. This module contains helper functions for controlling caching. It does so by
  3. managing the "Vary" header of responses. It includes functions to patch the
  4. header of response objects directly and decorators that change functions to do
  5. that header-patching themselves.
  6. For information on the Vary header, see RFC 9110 Section 12.5.5.
  7. Essentially, the "Vary" HTTP header defines which headers a cache should take
  8. into account when building its cache key. Requests with the same path but
  9. different header content for headers named in "Vary" need to get different
  10. cache keys to prevent delivery of wrong content.
  11. An example: i18n middleware would need to distinguish caches by the
  12. "Accept-language" header.
  13. """
  14. import time
  15. from collections import defaultdict
  16. from hashlib import md5
  17. from django.conf import settings
  18. from django.core.cache import caches
  19. from django.http import HttpResponse, HttpResponseNotModified
  20. from django.utils.http import http_date, parse_etags, parse_http_date_safe, quote_etag
  21. from django.utils.log import log_response
  22. from django.utils.regex_helper import _lazy_re_compile
  23. from django.utils.timezone import get_current_timezone_name
  24. from django.utils.translation import get_language
  25. cc_delim_re = _lazy_re_compile(r"\s*,\s*")
  26. def patch_cache_control(response, **kwargs):
  27. """
  28. Patch the Cache-Control header by adding all keyword arguments to it.
  29. The transformation is as follows:
  30. * All keyword parameter names are turned to lowercase, and underscores
  31. are converted to hyphens.
  32. * If the value of a parameter is True (exactly True, not just a
  33. true value), only the parameter name is added to the header.
  34. * All other parameters are added with their value, after applying
  35. str() to it.
  36. """
  37. def dictitem(s):
  38. t = s.split("=", 1)
  39. if len(t) > 1:
  40. return (t[0].lower(), t[1])
  41. else:
  42. return (t[0].lower(), True)
  43. def dictvalue(*t):
  44. if t[1] is True:
  45. return t[0]
  46. else:
  47. return "%s=%s" % (t[0], t[1])
  48. cc = defaultdict(set)
  49. if response.get("Cache-Control"):
  50. for field in cc_delim_re.split(response.headers["Cache-Control"]):
  51. directive, value = dictitem(field)
  52. if directive == "no-cache":
  53. # no-cache supports multiple field names.
  54. cc[directive].add(value)
  55. else:
  56. cc[directive] = value
  57. # If there's already a max-age header but we're being asked to set a new
  58. # max-age, use the minimum of the two ages. In practice this happens when
  59. # a decorator and a piece of middleware both operate on a given view.
  60. if "max-age" in cc and "max_age" in kwargs:
  61. kwargs["max_age"] = min(int(cc["max-age"]), kwargs["max_age"])
  62. # Allow overriding private caching and vice versa
  63. if "private" in cc and "public" in kwargs:
  64. del cc["private"]
  65. elif "public" in cc and "private" in kwargs:
  66. del cc["public"]
  67. for k, v in kwargs.items():
  68. directive = k.replace("_", "-")
  69. if directive == "no-cache":
  70. # no-cache supports multiple field names.
  71. cc[directive].add(v)
  72. else:
  73. cc[directive] = v
  74. directives = []
  75. for directive, values in cc.items():
  76. if isinstance(values, set):
  77. if True in values:
  78. # True takes precedence.
  79. values = {True}
  80. directives.extend([dictvalue(directive, value) for value in values])
  81. else:
  82. directives.append(dictvalue(directive, values))
  83. cc = ", ".join(directives)
  84. response.headers["Cache-Control"] = cc
  85. def get_max_age(response):
  86. """
  87. Return the max-age from the response Cache-Control header as an integer,
  88. or None if it wasn't found or wasn't an integer.
  89. """
  90. if not response.has_header("Cache-Control"):
  91. return
  92. cc = dict(
  93. _to_tuple(el) for el in cc_delim_re.split(response.headers["Cache-Control"])
  94. )
  95. try:
  96. return int(cc["max-age"])
  97. except (ValueError, TypeError, KeyError):
  98. pass
  99. def set_response_etag(response):
  100. if not response.streaming and response.content:
  101. response.headers["ETag"] = quote_etag(
  102. md5(response.content, usedforsecurity=False).hexdigest(),
  103. )
  104. return response
  105. def _precondition_failed(request):
  106. response = HttpResponse(status=412)
  107. log_response(
  108. "Precondition Failed: %s",
  109. request.path,
  110. response=response,
  111. request=request,
  112. )
  113. return response
  114. def _not_modified(request, response=None):
  115. new_response = HttpResponseNotModified()
  116. if response:
  117. # Preserve the headers required by RFC 9110 Section 15.4.5, as well as
  118. # Last-Modified.
  119. for header in (
  120. "Cache-Control",
  121. "Content-Location",
  122. "Date",
  123. "ETag",
  124. "Expires",
  125. "Last-Modified",
  126. "Vary",
  127. ):
  128. if header in response:
  129. new_response.headers[header] = response.headers[header]
  130. # Preserve cookies as per the cookie specification: "If a proxy server
  131. # receives a response which contains a Set-cookie header, it should
  132. # propagate the Set-cookie header to the client, regardless of whether
  133. # the response was 304 (Not Modified) or 200 (OK).
  134. # https://curl.haxx.se/rfc/cookie_spec.html
  135. new_response.cookies = response.cookies
  136. return new_response
  137. def get_conditional_response(request, etag=None, last_modified=None, response=None):
  138. # Only return conditional responses on successful requests.
  139. if response and not (200 <= response.status_code < 300):
  140. return response
  141. # Get HTTP request headers.
  142. if_match_etags = parse_etags(request.META.get("HTTP_IF_MATCH", ""))
  143. if_unmodified_since = request.META.get("HTTP_IF_UNMODIFIED_SINCE")
  144. if_unmodified_since = if_unmodified_since and parse_http_date_safe(
  145. if_unmodified_since
  146. )
  147. if_none_match_etags = parse_etags(request.META.get("HTTP_IF_NONE_MATCH", ""))
  148. if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE")
  149. if_modified_since = if_modified_since and parse_http_date_safe(if_modified_since)
  150. # Evaluation of request preconditions below follows RFC 9110 Section
  151. # 13.2.2.
  152. # Step 1: Test the If-Match precondition.
  153. if if_match_etags and not _if_match_passes(etag, if_match_etags):
  154. return _precondition_failed(request)
  155. # Step 2: Test the If-Unmodified-Since precondition.
  156. if (
  157. not if_match_etags
  158. and if_unmodified_since
  159. and not _if_unmodified_since_passes(last_modified, if_unmodified_since)
  160. ):
  161. return _precondition_failed(request)
  162. # Step 3: Test the If-None-Match precondition.
  163. if if_none_match_etags and not _if_none_match_passes(etag, if_none_match_etags):
  164. if request.method in ("GET", "HEAD"):
  165. return _not_modified(request, response)
  166. else:
  167. return _precondition_failed(request)
  168. # Step 4: Test the If-Modified-Since precondition.
  169. if (
  170. not if_none_match_etags
  171. and if_modified_since
  172. and not _if_modified_since_passes(last_modified, if_modified_since)
  173. and request.method in ("GET", "HEAD")
  174. ):
  175. return _not_modified(request, response)
  176. # Step 5: Test the If-Range precondition (not supported).
  177. # Step 6: Return original response since there isn't a conditional response.
  178. return response
  179. def _if_match_passes(target_etag, etags):
  180. """
  181. Test the If-Match comparison as defined in RFC 9110 Section 13.1.1.
  182. """
  183. if not target_etag:
  184. # If there isn't an ETag, then there can't be a match.
  185. return False
  186. elif etags == ["*"]:
  187. # The existence of an ETag means that there is "a current
  188. # representation for the target resource", even if the ETag is weak,
  189. # so there is a match to '*'.
  190. return True
  191. elif target_etag.startswith("W/"):
  192. # A weak ETag can never strongly match another ETag.
  193. return False
  194. else:
  195. # Since the ETag is strong, this will only return True if there's a
  196. # strong match.
  197. return target_etag in etags
  198. def _if_unmodified_since_passes(last_modified, if_unmodified_since):
  199. """
  200. Test the If-Unmodified-Since comparison as defined in RFC 9110 Section
  201. 13.1.4.
  202. """
  203. return last_modified and last_modified <= if_unmodified_since
  204. def _if_none_match_passes(target_etag, etags):
  205. """
  206. Test the If-None-Match comparison as defined in RFC 9110 Section 13.1.2.
  207. """
  208. if not target_etag:
  209. # If there isn't an ETag, then there isn't a match.
  210. return True
  211. elif etags == ["*"]:
  212. # The existence of an ETag means that there is "a current
  213. # representation for the target resource", so there is a match to '*'.
  214. return False
  215. else:
  216. # The comparison should be weak, so look for a match after stripping
  217. # off any weak indicators.
  218. target_etag = target_etag.strip("W/")
  219. etags = (etag.strip("W/") for etag in etags)
  220. return target_etag not in etags
  221. def _if_modified_since_passes(last_modified, if_modified_since):
  222. """
  223. Test the If-Modified-Since comparison as defined in RFC 9110 Section
  224. 13.1.3.
  225. """
  226. return not last_modified or last_modified > if_modified_since
  227. def patch_response_headers(response, cache_timeout=None):
  228. """
  229. Add HTTP caching headers to the given HttpResponse: Expires and
  230. Cache-Control.
  231. Each header is only added if it isn't already set.
  232. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used
  233. by default.
  234. """
  235. if cache_timeout is None:
  236. cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  237. if cache_timeout < 0:
  238. cache_timeout = 0 # Can't have max-age negative
  239. if not response.has_header("Expires"):
  240. response.headers["Expires"] = http_date(time.time() + cache_timeout)
  241. patch_cache_control(response, max_age=cache_timeout)
  242. def add_never_cache_headers(response):
  243. """
  244. Add headers to a response to indicate that a page should never be cached.
  245. """
  246. patch_response_headers(response, cache_timeout=-1)
  247. patch_cache_control(
  248. response, no_cache=True, no_store=True, must_revalidate=True, private=True
  249. )
  250. def patch_vary_headers(response, newheaders):
  251. """
  252. Add (or update) the "Vary" header in the given HttpResponse object.
  253. newheaders is a list of header names that should be in "Vary". If headers
  254. contains an asterisk, then "Vary" header will consist of a single asterisk
  255. '*'. Otherwise, existing headers in "Vary" aren't removed.
  256. """
  257. # Note that we need to keep the original order intact, because cache
  258. # implementations may rely on the order of the Vary contents in, say,
  259. # computing an MD5 hash.
  260. if response.has_header("Vary"):
  261. vary_headers = cc_delim_re.split(response.headers["Vary"])
  262. else:
  263. vary_headers = []
  264. # Use .lower() here so we treat headers as case-insensitive.
  265. existing_headers = {header.lower() for header in vary_headers}
  266. additional_headers = [
  267. newheader
  268. for newheader in newheaders
  269. if newheader.lower() not in existing_headers
  270. ]
  271. vary_headers += additional_headers
  272. if "*" in vary_headers:
  273. response.headers["Vary"] = "*"
  274. else:
  275. response.headers["Vary"] = ", ".join(vary_headers)
  276. def has_vary_header(response, header_query):
  277. """
  278. Check to see if the response has a given header name in its Vary header.
  279. """
  280. if not response.has_header("Vary"):
  281. return False
  282. vary_headers = cc_delim_re.split(response.headers["Vary"])
  283. existing_headers = {header.lower() for header in vary_headers}
  284. return header_query.lower() in existing_headers
  285. def _i18n_cache_key_suffix(request, cache_key):
  286. """If necessary, add the current locale or time zone to the cache key."""
  287. if settings.USE_I18N:
  288. # first check if LocaleMiddleware or another middleware added
  289. # LANGUAGE_CODE to request, then fall back to the active language
  290. # which in turn can also fall back to settings.LANGUAGE_CODE
  291. cache_key += ".%s" % getattr(request, "LANGUAGE_CODE", get_language())
  292. if settings.USE_TZ:
  293. cache_key += ".%s" % get_current_timezone_name()
  294. return cache_key
  295. def _generate_cache_key(request, method, headerlist, key_prefix):
  296. """Return a cache key from the headers given in the header list."""
  297. ctx = md5(usedforsecurity=False)
  298. for header in headerlist:
  299. value = request.META.get(header)
  300. if value is not None:
  301. ctx.update(value.encode())
  302. url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False)
  303. cache_key = "views.decorators.cache.cache_page.%s.%s.%s.%s" % (
  304. key_prefix,
  305. method,
  306. url.hexdigest(),
  307. ctx.hexdigest(),
  308. )
  309. return _i18n_cache_key_suffix(request, cache_key)
  310. def _generate_cache_header_key(key_prefix, request):
  311. """Return a cache key for the header cache."""
  312. url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False)
  313. cache_key = "views.decorators.cache.cache_header.%s.%s" % (
  314. key_prefix,
  315. url.hexdigest(),
  316. )
  317. return _i18n_cache_key_suffix(request, cache_key)
  318. def get_cache_key(request, key_prefix=None, method="GET", cache=None):
  319. """
  320. Return a cache key based on the request URL and query. It can be used
  321. in the request phase because it pulls the list of headers to take into
  322. account from the global URL registry and uses those to build a cache key
  323. to check against.
  324. If there isn't a headerlist stored, return None, indicating that the page
  325. needs to be rebuilt.
  326. """
  327. if key_prefix is None:
  328. key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  329. cache_key = _generate_cache_header_key(key_prefix, request)
  330. if cache is None:
  331. cache = caches[settings.CACHE_MIDDLEWARE_ALIAS]
  332. headerlist = cache.get(cache_key)
  333. if headerlist is not None:
  334. return _generate_cache_key(request, method, headerlist, key_prefix)
  335. else:
  336. return None
  337. def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
  338. """
  339. Learn what headers to take into account for some request URL from the
  340. response object. Store those headers in a global URL registry so that
  341. later access to that URL will know what headers to take into account
  342. without building the response object itself. The headers are named in the
  343. Vary header of the response, but we want to prevent response generation.
  344. The list of headers to use for cache key generation is stored in the same
  345. cache as the pages themselves. If the cache ages some data out of the
  346. cache, this just means that we have to build the response once to get at
  347. the Vary header and so at the list of headers to use for the cache key.
  348. """
  349. if key_prefix is None:
  350. key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  351. if cache_timeout is None:
  352. cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  353. cache_key = _generate_cache_header_key(key_prefix, request)
  354. if cache is None:
  355. cache = caches[settings.CACHE_MIDDLEWARE_ALIAS]
  356. if response.has_header("Vary"):
  357. is_accept_language_redundant = settings.USE_I18N
  358. # If i18n is used, the generated cache key will be suffixed with the
  359. # current locale. Adding the raw value of Accept-Language is redundant
  360. # in that case and would result in storing the same content under
  361. # multiple keys in the cache. See #18191 for details.
  362. headerlist = []
  363. for header in cc_delim_re.split(response.headers["Vary"]):
  364. header = header.upper().replace("-", "_")
  365. if header != "ACCEPT_LANGUAGE" or not is_accept_language_redundant:
  366. headerlist.append("HTTP_" + header)
  367. headerlist.sort()
  368. cache.set(cache_key, headerlist, cache_timeout)
  369. return _generate_cache_key(request, request.method, headerlist, key_prefix)
  370. else:
  371. # if there is no Vary header, we still need a cache key
  372. # for the request.build_absolute_uri()
  373. cache.set(cache_key, [], cache_timeout)
  374. return _generate_cache_key(request, request.method, [], key_prefix)
  375. def _to_tuple(s):
  376. t = s.split("=", 1)
  377. if len(t) == 2:
  378. return t[0].lower(), t[1]
  379. return t[0].lower(), True