You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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