2008-08-09 23:07:45 +08:00
|
|
|
"""
|
|
|
|
Cache middleware. If enabled, each Django-powered page will be cached based on
|
2008-08-16 01:47:03 +08:00
|
|
|
URL. The canonical way to enable cache middleware is to set
|
2008-08-09 23:07:45 +08:00
|
|
|
``UpdateCacheMiddleware`` as your first piece of middleware, and
|
|
|
|
``FetchFromCacheMiddleware`` as the last::
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
MIDDLEWARE = [
|
2008-08-09 23:07:45 +08:00
|
|
|
'django.middleware.cache.UpdateCacheMiddleware',
|
|
|
|
...
|
|
|
|
'django.middleware.cache.FetchFromCacheMiddleware'
|
|
|
|
]
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
This is counter-intuitive, but correct: ``UpdateCacheMiddleware`` needs to run
|
|
|
|
last during the response phase, which processes middleware bottom-up;
|
|
|
|
``FetchFromCacheMiddleware`` needs to run last during the request phase, which
|
|
|
|
processes middleware top-down.
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2008-08-16 01:47:03 +08:00
|
|
|
The single-class ``CacheMiddleware`` can be used for some simple sites.
|
|
|
|
However, if any other piece of middleware needs to affect the cache key, you'll
|
|
|
|
need to use the two-part ``UpdateCacheMiddleware`` and
|
|
|
|
``FetchFromCacheMiddleware``. This'll most often happen when you're using
|
|
|
|
Django's ``LocaleMiddleware``.
|
2007-11-30 00:57:18 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
More details about how the caching works:
|
2006-07-20 23:37:12 +08:00
|
|
|
|
2011-03-02 20:47:36 +08:00
|
|
|
* Only GET or HEAD-requests with status code 200 are cached.
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
* The number of seconds each page is stored for is set by the "max-age" section
|
|
|
|
of the response's "Cache-Control" header, falling back to the
|
|
|
|
CACHE_MIDDLEWARE_SECONDS setting if the section was not found.
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2010-10-29 09:31:15 +08:00
|
|
|
* This middleware expects that a HEAD request is answered with the same response
|
|
|
|
headers exactly like the corresponding GET request.
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
* When a hit occurs, a shallow copy of the original response object is returned
|
|
|
|
from process_request.
|
2006-08-18 11:31:13 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
* Pages will be cached based on the contents of the request headers listed in
|
|
|
|
the response's "Vary" header.
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
* This middleware also sets ETag, Last-Modified, Expires and Cache-Control
|
|
|
|
headers on the response object.
|
2006-07-20 23:37:12 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
"""
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
from django.conf import settings
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.cache import DEFAULT_CACHE_ALIAS, caches
|
|
|
|
from django.utils.cache import (
|
|
|
|
get_cache_key, get_max_age, has_vary_header, learn_cache_key,
|
|
|
|
patch_response_headers,
|
|
|
|
)
|
2015-11-07 23:12:37 +08:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2011-01-24 22:24:35 +08:00
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
class UpdateCacheMiddleware(MiddlewareMixin):
|
2008-08-09 23:07:45 +08:00
|
|
|
"""
|
|
|
|
Response-phase cache middleware that updates the cache if the response is
|
|
|
|
cacheable.
|
2008-08-16 01:47:03 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
Must be used as part of the two-part update/fetch cache middleware.
|
2015-11-07 23:12:37 +08:00
|
|
|
UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE
|
|
|
|
so that it'll get called last during the response phase.
|
2008-08-09 23:07:45 +08:00
|
|
|
"""
|
2021-01-13 03:55:32 +08:00
|
|
|
def __init__(self, get_response):
|
2020-08-25 04:25:33 +08:00
|
|
|
super().__init__(get_response)
|
2008-08-09 23:07:45 +08:00
|
|
|
self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
|
2019-09-27 02:41:38 +08:00
|
|
|
self.page_timeout = None
|
2008-08-09 23:07:45 +08:00
|
|
|
self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
|
2011-01-24 14:36:31 +08:00
|
|
|
self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
|
2021-11-01 08:54:13 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def cache(self):
|
|
|
|
return caches[self.cache_alias]
|
2005-07-19 03:07:37 +08:00
|
|
|
|
2011-02-01 08:20:31 +08:00
|
|
|
def _should_update_cache(self, request, response):
|
2014-03-21 21:46:17 +08:00
|
|
|
return hasattr(request, '_cache_update_cache') and request._cache_update_cache
|
2011-02-01 08:20:31 +08:00
|
|
|
|
2005-07-19 03:07:37 +08:00
|
|
|
def process_response(self, request, response):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Set the cache, if needed."""
|
2011-02-01 08:20:31 +08:00
|
|
|
if not self._should_update_cache(request, response):
|
2005-10-09 08:55:08 +08:00
|
|
|
# We don't need to update the cache, just return.
|
|
|
|
return response
|
2014-04-21 04:10:32 +08:00
|
|
|
|
2016-09-12 22:19:36 +08:00
|
|
|
if response.streaming or response.status_code not in (200, 304):
|
2005-10-09 08:55:08 +08:00
|
|
|
return response
|
2014-04-21 04:10:32 +08:00
|
|
|
|
|
|
|
# Don't cache responses that set a user-specific (and maybe security
|
|
|
|
# sensitive) cookie in response to a cookie-less request.
|
|
|
|
if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
|
|
|
|
return response
|
|
|
|
|
2018-02-06 13:44:53 +08:00
|
|
|
# Don't cache a response with 'Cache-Control: private'
|
|
|
|
if 'private' in response.get('Cache-Control', ()):
|
|
|
|
return response
|
|
|
|
|
2019-09-27 02:41:38 +08:00
|
|
|
# Page timeout takes precedence over the "max-age" and the default
|
|
|
|
# cache timeout.
|
|
|
|
timeout = self.page_timeout
|
2013-10-10 21:35:56 +08:00
|
|
|
if timeout is None:
|
2019-09-27 02:41:38 +08:00
|
|
|
# The timeout from the "max-age" section of the "Cache-Control"
|
|
|
|
# header takes precedence over the default cache timeout.
|
|
|
|
timeout = get_max_age(response)
|
|
|
|
if timeout is None:
|
|
|
|
timeout = self.cache_timeout
|
|
|
|
elif timeout == 0:
|
|
|
|
# max-age was set to 0, don't cache.
|
|
|
|
return response
|
2007-11-30 00:57:18 +08:00
|
|
|
patch_response_headers(response, timeout)
|
2016-09-12 22:19:36 +08:00
|
|
|
if timeout and response.status_code == 200:
|
2010-12-22 15:52:44 +08:00
|
|
|
cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
|
2011-01-24 22:24:35 +08:00
|
|
|
if hasattr(response, 'render') and callable(response.render):
|
|
|
|
response.add_post_render_callback(
|
|
|
|
lambda r: self.cache.set(cache_key, r, timeout)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
self.cache.set(cache_key, response, timeout)
|
2005-07-19 03:07:37 +08:00
|
|
|
return response
|
2008-08-09 23:07:45 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
class FetchFromCacheMiddleware(MiddlewareMixin):
|
2008-08-09 23:07:45 +08:00
|
|
|
"""
|
|
|
|
Request-phase cache middleware that fetches a page from the cache.
|
2008-08-16 01:47:03 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
Must be used as part of the two-part update/fetch cache middleware.
|
2015-11-07 23:12:37 +08:00
|
|
|
FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE
|
|
|
|
so that it'll get called last during the request phase.
|
2008-08-09 23:07:45 +08:00
|
|
|
"""
|
2021-01-13 03:55:32 +08:00
|
|
|
def __init__(self, get_response):
|
2020-08-25 04:25:33 +08:00
|
|
|
super().__init__(get_response)
|
2008-08-09 23:07:45 +08:00
|
|
|
self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
|
2011-01-24 14:36:31 +08:00
|
|
|
self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
|
2021-11-01 08:54:13 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def cache(self):
|
|
|
|
return caches[self.cache_alias]
|
2008-08-16 01:47:03 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
def process_request(self, request):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Check whether the page is already cached and return the cached
|
2008-08-09 23:07:45 +08:00
|
|
|
version if available.
|
|
|
|
"""
|
2014-03-31 03:11:05 +08:00
|
|
|
if request.method not in ('GET', 'HEAD'):
|
2008-08-09 23:07:45 +08:00
|
|
|
request._cache_update_cache = False
|
2013-11-03 05:02:56 +08:00
|
|
|
return None # Don't bother checking the cache.
|
2008-08-09 23:07:45 +08:00
|
|
|
|
2010-10-29 09:31:15 +08:00
|
|
|
# try and get the cached GET response
|
2010-12-22 15:52:44 +08:00
|
|
|
cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
|
2008-08-09 23:07:45 +08:00
|
|
|
if cache_key is None:
|
|
|
|
request._cache_update_cache = True
|
2013-11-03 05:02:56 +08:00
|
|
|
return None # No cache information available, need to rebuild.
|
2015-05-14 02:51:18 +08:00
|
|
|
response = self.cache.get(cache_key)
|
2010-10-29 09:31:15 +08:00
|
|
|
# if it wasn't found and we are looking for a HEAD, try looking just for that
|
|
|
|
if response is None and request.method == 'HEAD':
|
2010-12-22 15:52:44 +08:00
|
|
|
cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache)
|
2015-05-14 02:51:18 +08:00
|
|
|
response = self.cache.get(cache_key)
|
2010-10-29 09:31:15 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
if response is None:
|
|
|
|
request._cache_update_cache = True
|
2013-11-03 05:02:56 +08:00
|
|
|
return None # No cache information available, need to rebuild.
|
2008-08-09 23:07:45 +08:00
|
|
|
|
2010-10-29 09:31:15 +08:00
|
|
|
# hit, return cached response
|
2008-08-09 23:07:45 +08:00
|
|
|
request._cache_update_cache = False
|
|
|
|
return response
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
|
|
|
|
"""
|
|
|
|
Cache middleware that provides basic behavior for many simple sites.
|
2008-08-16 01:47:03 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
Also used as the hook point for the cache decorator, which is generated
|
|
|
|
using the decorator-from-middleware utility.
|
|
|
|
"""
|
2021-01-13 03:55:32 +08:00
|
|
|
def __init__(self, get_response, cache_timeout=None, page_timeout=None, **kwargs):
|
2020-08-25 04:25:33 +08:00
|
|
|
super().__init__(get_response)
|
2010-12-21 23:19:19 +08:00
|
|
|
# We need to differentiate between "provided, but using default value",
|
|
|
|
# and "not provided". If the value is provided using a default, then
|
|
|
|
# we fall back to system defaults. If it is not provided at all,
|
|
|
|
# we need to use middleware defaults.
|
2010-12-22 15:52:44 +08:00
|
|
|
|
|
|
|
try:
|
2013-10-19 06:49:24 +08:00
|
|
|
key_prefix = kwargs['key_prefix']
|
|
|
|
if key_prefix is None:
|
|
|
|
key_prefix = ''
|
2020-08-25 04:25:33 +08:00
|
|
|
self.key_prefix = key_prefix
|
2010-12-22 15:52:44 +08:00
|
|
|
except KeyError:
|
2020-08-25 04:25:33 +08:00
|
|
|
pass
|
2010-12-21 23:19:19 +08:00
|
|
|
try:
|
2013-10-19 06:49:24 +08:00
|
|
|
cache_alias = kwargs['cache_alias']
|
|
|
|
if cache_alias is None:
|
|
|
|
cache_alias = DEFAULT_CACHE_ALIAS
|
2020-08-25 04:25:33 +08:00
|
|
|
self.cache_alias = cache_alias
|
2010-12-21 23:19:19 +08:00
|
|
|
except KeyError:
|
2020-08-25 04:25:33 +08:00
|
|
|
pass
|
2013-10-19 06:49:24 +08:00
|
|
|
|
2020-08-25 04:25:33 +08:00
|
|
|
if cache_timeout is not None:
|
|
|
|
self.cache_timeout = cache_timeout
|
2019-09-27 02:41:38 +08:00
|
|
|
self.page_timeout = page_timeout
|