cache.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
  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. from __future__ import unicode_literals
  16. import hashlib
  17. import re
  18. import time
  19. from django.conf import settings
  20. from django.core.cache import caches
  21. from django.utils.encoding import iri_to_uri, force_bytes, force_text
  22. from django.utils.http import http_date
  23. from django.utils.timezone import get_current_timezone_name
  24. from django.utils.translation import get_language
  25. cc_delim_re = re.compile(r'\s*,\s*')
  26. def patch_cache_control(response, **kwargs):
  27. """
  28. This function patches the Cache-Control header by adding all
  29. keyword arguments to it. 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. if response.has_header('Cache-Control'):
  49. cc = cc_delim_re.split(response['Cache-Control'])
  50. cc = dict(dictitem(el) for el in cc)
  51. else:
  52. cc = {}
  53. # If there's already a max-age header but we're being asked to set a new
  54. # max-age, use the minimum of the two ages. In practice this happens when
  55. # a decorator and a piece of middleware both operate on a given view.
  56. if 'max-age' in cc and 'max_age' in kwargs:
  57. kwargs['max_age'] = min(int(cc['max-age']), kwargs['max_age'])
  58. # Allow overriding private caching and vice versa
  59. if 'private' in cc and 'public' in kwargs:
  60. del cc['private']
  61. elif 'public' in cc and 'private' in kwargs:
  62. del cc['public']
  63. for (k, v) in kwargs.items():
  64. cc[k.replace('_', '-')] = v
  65. cc = ', '.join(dictvalue(el) for el in cc.items())
  66. response['Cache-Control'] = cc
  67. def get_max_age(response):
  68. """
  69. Returns the max-age from the response Cache-Control header as an integer
  70. (or ``None`` if it wasn't found or wasn't an integer.
  71. """
  72. if not response.has_header('Cache-Control'):
  73. return
  74. cc = dict(_to_tuple(el) for el in
  75. cc_delim_re.split(response['Cache-Control']))
  76. if 'max-age' in cc:
  77. try:
  78. return int(cc['max-age'])
  79. except (ValueError, TypeError):
  80. pass
  81. def _set_response_etag(response):
  82. if not response.streaming:
  83. response['ETag'] = '"%s"' % hashlib.md5(response.content).hexdigest()
  84. return response
  85. def patch_response_headers(response, cache_timeout=None):
  86. """
  87. Adds some useful headers to the given HttpResponse object:
  88. ETag, Last-Modified, Expires and Cache-Control
  89. Each header is only added if it isn't already set.
  90. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used
  91. by default.
  92. """
  93. if cache_timeout is None:
  94. cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  95. if cache_timeout < 0:
  96. cache_timeout = 0 # Can't have max-age negative
  97. if settings.USE_ETAGS and not response.has_header('ETag'):
  98. if hasattr(response, 'render') and callable(response.render):
  99. response.add_post_render_callback(_set_response_etag)
  100. else:
  101. response = _set_response_etag(response)
  102. if not response.has_header('Last-Modified'):
  103. response['Last-Modified'] = http_date()
  104. if not response.has_header('Expires'):
  105. response['Expires'] = http_date(time.time() + cache_timeout)
  106. patch_cache_control(response, max_age=cache_timeout)
  107. def add_never_cache_headers(response):
  108. """
  109. Adds headers to a response to indicate that a page should never be cached.
  110. """
  111. patch_response_headers(response, cache_timeout=-1)
  112. def patch_vary_headers(response, newheaders):
  113. """
  114. Adds (or updates) the "Vary" header in the given HttpResponse object.
  115. newheaders is a list of header names that should be in "Vary". Existing
  116. headers in "Vary" aren't removed.
  117. """
  118. # Note that we need to keep the original order intact, because cache
  119. # implementations may rely on the order of the Vary contents in, say,
  120. # computing an MD5 hash.
  121. if response.has_header('Vary'):
  122. vary_headers = cc_delim_re.split(response['Vary'])
  123. else:
  124. vary_headers = []
  125. # Use .lower() here so we treat headers as case-insensitive.
  126. existing_headers = set(header.lower() for header in vary_headers)
  127. additional_headers = [newheader for newheader in newheaders
  128. if newheader.lower() not in existing_headers]
  129. response['Vary'] = ', '.join(vary_headers + additional_headers)
  130. def has_vary_header(response, header_query):
  131. """
  132. Checks to see if the response has a given header name in its Vary header.
  133. """
  134. if not response.has_header('Vary'):
  135. return False
  136. vary_headers = cc_delim_re.split(response['Vary'])
  137. existing_headers = set(header.lower() for header in vary_headers)
  138. return header_query.lower() in existing_headers
  139. def _i18n_cache_key_suffix(request, cache_key):
  140. """If necessary, adds the current locale or time zone to the cache key."""
  141. if settings.USE_I18N or settings.USE_L10N:
  142. # first check if LocaleMiddleware or another middleware added
  143. # LANGUAGE_CODE to request, then fall back to the active language
  144. # which in turn can also fall back to settings.LANGUAGE_CODE
  145. cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
  146. if settings.USE_TZ:
  147. # The datetime module doesn't restrict the output of tzname().
  148. # Windows is known to use non-standard, locale-dependent names.
  149. # User-defined tzinfo classes may return absolutely anything.
  150. # Hence this paranoid conversion to create a valid cache key.
  151. tz_name = force_text(get_current_timezone_name(), errors='ignore')
  152. cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
  153. return cache_key
  154. def _generate_cache_key(request, method, headerlist, key_prefix):
  155. """Returns a cache key from the headers given in the header list."""
  156. ctx = hashlib.md5()
  157. for header in headerlist:
  158. value = request.META.get(header, None)
  159. if value is not None:
  160. ctx.update(force_bytes(value))
  161. url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
  162. cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
  163. key_prefix, method, url.hexdigest(), ctx.hexdigest())
  164. return _i18n_cache_key_suffix(request, cache_key)
  165. def _generate_cache_header_key(key_prefix, request):
  166. """Returns a cache key for the header cache."""
  167. url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
  168. cache_key = 'views.decorators.cache.cache_header.%s.%s' % (
  169. key_prefix, url.hexdigest())
  170. return _i18n_cache_key_suffix(request, cache_key)
  171. def get_cache_key(request, key_prefix=None, method='GET', cache=None):
  172. """
  173. Returns a cache key based on the request URL and query. It can be used
  174. in the request phase because it pulls the list of headers to take into
  175. account from the global URL registry and uses those to build a cache key
  176. to check against.
  177. If there is no headerlist stored, the page needs to be rebuilt, so this
  178. function returns None.
  179. """
  180. if key_prefix is None:
  181. key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  182. cache_key = _generate_cache_header_key(key_prefix, request)
  183. if cache is None:
  184. cache = caches[settings.CACHE_MIDDLEWARE_ALIAS]
  185. headerlist = cache.get(cache_key, None)
  186. if headerlist is not None:
  187. return _generate_cache_key(request, method, headerlist, key_prefix)
  188. else:
  189. return None
  190. def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
  191. """
  192. Learns what headers to take into account for some request URL from the
  193. response object. It stores those headers in a global URL registry so that
  194. later access to that URL will know what headers to take into account
  195. without building the response object itself. The headers are named in the
  196. Vary header of the response, but we want to prevent response generation.
  197. The list of headers to use for cache key generation is stored in the same
  198. cache as the pages themselves. If the cache ages some data out of the
  199. cache, this just means that we have to build the response once to get at
  200. the Vary header and so at the list of headers to use for the cache key.
  201. """
  202. if key_prefix is None:
  203. key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  204. if cache_timeout is None:
  205. cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  206. cache_key = _generate_cache_header_key(key_prefix, request)
  207. if cache is None:
  208. cache = caches[settings.CACHE_MIDDLEWARE_ALIAS]
  209. if response.has_header('Vary'):
  210. is_accept_language_redundant = settings.USE_I18N or settings.USE_L10N
  211. # If i18n or l10n are used, the generated cache key will be suffixed
  212. # with the current locale. Adding the raw value of Accept-Language is
  213. # redundant in that case and would result in storing the same content
  214. # under multiple keys in the cache. See #18191 for details.
  215. headerlist = []
  216. for header in cc_delim_re.split(response['Vary']):
  217. header = header.upper().replace('-', '_')
  218. if header == 'ACCEPT_LANGUAGE' and is_accept_language_redundant:
  219. continue
  220. headerlist.append('HTTP_' + header)
  221. headerlist.sort()
  222. cache.set(cache_key, headerlist, cache_timeout)
  223. return _generate_cache_key(request, request.method, headerlist, key_prefix)
  224. else:
  225. # if there is no Vary header, we still need a cache key
  226. # for the request.build_absolute_uri()
  227. cache.set(cache_key, [], cache_timeout)
  228. return _generate_cache_key(request, request.method, [], key_prefix)
  229. def _to_tuple(s):
  230. t = s.split('=', 1)
  231. if len(t) == 2:
  232. return t[0].lower(), t[1]
  233. return t[0].lower(), True