Debian Codegraph @

django/middleware/cache.py

raw
1 """
2 Cache middleware. If enabled, each Django-powered page will be cached based on
3 URL. The canonical way to enable cache middleware is to set
4 ``UpdateCacheMiddleware`` as your first piece of middleware, and
5 ``FetchFromCacheMiddleware`` as the last::
6
7 MIDDLEWARE = [
8 'django.middleware.cache.UpdateCacheMiddleware',
9 ...
10 'django.middleware.cache.FetchFromCacheMiddleware'
11 ]
12
13 This is counterintuitive, but correct: ``UpdateCacheMiddleware`` needs to run
14 last during the response phase, which processes middleware bottom-up;
15 ``FetchFromCacheMiddleware`` needs to run last during the request phase, which
16 processes middleware top-down.
17
18 The single-class ``CacheMiddleware`` can be used for some simple sites.
19 However, if any other piece of middleware needs to affect the cache key, you'll
20 need to use the two-part ``UpdateCacheMiddleware`` and
21 ``FetchFromCacheMiddleware``. This'll most often happen when you're using
22 Django's ``LocaleMiddleware``.
23
24 More details about how the caching works:
25
26 * Only GET or HEAD-requests with status code 200 are cached.
27
28 * The number of seconds each page is stored for is set by the "max-age" section
29 of the response's "Cache-Control" header, falling back to the
30 CACHE_MIDDLEWARE_SECONDS setting if the section was not found.
31
32 * This middleware expects that a HEAD request is answered with the same response
33 headers exactly like the corresponding GET request.
34
35 * When a hit occurs, a shallow copy of the original response object is returned
36 from process_request.
37
38 * Pages will be cached based on the contents of the request headers listed in
39 the response's "Vary" header.
40
41 * This middleware also sets ETag, Last-Modified, Expires and Cache-Control
42 headers on the response object.
43
44 * If the request had an Authorization header and the response was not marked
45 "Cache-Control: public", the response will vary on Authorization.
46 """
47
48 import time
49
50 from django.conf import settings
51 from django.core.cache import DEFAULT_CACHE_ALIAS, caches
52 from django.utils.cache import (
53 get_cache_key,
54 get_max_age,
55 has_vary_header,
56 learn_cache_key,
57 patch_response_headers,
58 patch_vary_headers,
59 )
60 from django.utils.deprecation import MiddlewareMixin
61 from django.utils.http import parse_http_date_safe
62
63
64 class UpdateCacheMiddleware(MiddlewareMixin):
65 """
66 Response-phase cache middleware that updates the cache if the response is
67 cacheable.
68
69 Must be used as part of the two-part update/fetch cache middleware.
70 UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE
71 so that it'll get called last during the response phase.
72 """
73
74 def __init__(self, get_response):
75 super().__init__(get_response)
76 self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
77 self.page_timeout = None
78 self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
79 self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
80
81 @property
82 def cache(self):
83 return caches[self.cache_alias]
84
85 def _should_update_cache(self, request, response):
86 return hasattr(request, "_cache_update_cache") and request._cache_update_cache
87
88 def process_response(self, request, response):
89 """Set the cache, if needed."""
90 if not self._should_update_cache(request, response):
91 # We don't need to update the cache, just return.
92 return response
93
94 if response.streaming or response.status_code not in (200, 304):
95 return response
96
97 # Don't cache responses that set a user-specific (and maybe security
98 # sensitive) cookie in response to a cookie-less request.
99 if (
100 not request.COOKIES
101 and response.cookies
102 and has_vary_header(response, "Cookie")
103 ):
104 return response
105
106 # Don't cache responses when the Cache-Control header is set to
107 # private, no-cache, or no-store.
108 cache_control = response.get("Cache-Control", "").lower()
109 if cache_control and any(
110 directive in cache_control
111 for directive in (
112 "private",
113 "no-cache",
114 "no-store",
115 )
116 ):
117 return response
118
119 # Don't cache responses when the Vary header contains '*'.
120 if has_vary_header(response, "*"):
121 return response
122
123 # Page timeout takes precedence over the "max-age" and the default
124 # cache timeout.
125 timeout = self.page_timeout
126 if timeout is None:
127 # The timeout from the "max-age" section of the "Cache-Control"
128 # header takes precedence over the default cache timeout.
129 timeout = get_max_age(response)
130 if timeout is None:
131 timeout = self.cache_timeout
132 elif timeout == 0:
133 # max-age was set to 0, don't cache.
134 return response
135 patch_response_headers(response, timeout)
136 # Make the response vary on Authorization if the request bears that
137 # header, unless allowed by "public" per RFC 9111, Section 3.5. No
138 # exceptions are made for "s-maxage" and "must-revalidate" since these
139 # are not currently implemented by Django.
140 if request.headers.get("Authorization") and "public" not in cache_control:
141 patch_vary_headers(response, ("Authorization",))
142 if timeout and response.status_code == 200:
143 cache_key = learn_cache_key(
144 request, response, timeout, self.key_prefix, cache=self.cache
145 )
146 if hasattr(response, "render") and callable(response.render):
147 response.add_post_render_callback(
148 lambda r: self.cache.set(cache_key, r, timeout)
149 )
150 else:
151 self.cache.set(cache_key, response, timeout)
152 return response
153
154
155 class FetchFromCacheMiddleware(MiddlewareMixin):
156 """
157 Request-phase cache middleware that fetches a page from the cache.
158
159 Must be used as part of the two-part update/fetch cache middleware.
160 FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE
161 so that it'll get called last during the request phase.
162 """
163
164 def __init__(self, get_response):
165 super().__init__(get_response)
166 self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
167 self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
168
169 @property
170 def cache(self):
171 return caches[self.cache_alias]
172
173 def process_request(self, request):
174 """
175 Check whether the page is already cached and return the cached
176 version if available.
177 """
178 if request.method not in ("GET", "HEAD"):
179 request._cache_update_cache = False
180 return None # Don't bother checking the cache.
181
182 # try and get the cached GET response
183 cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache)
184 if cache_key is None:
185 request._cache_update_cache = True
186 return None # No cache information available, need to rebuild.
187 response = self.cache.get(cache_key)
188 # if it wasn't found and we are looking for a HEAD, try looking just for that
189 if response is None and request.method == "HEAD":
190 cache_key = get_cache_key(
191 request, self.key_prefix, "HEAD", cache=self.cache
192 )
193 response = self.cache.get(cache_key)
194
195 if response is None:
196 request._cache_update_cache = True
197 return None # No cache information available, need to rebuild.
198
199 # Derive the age estimation of the cached response.
200 if (max_age_seconds := get_max_age(response)) is not None and (
201 expires_timestamp := parse_http_date_safe(response["Expires"])
202 ) is not None:
203 now_timestamp = int(time.time())
204 remaining_seconds = expires_timestamp - now_timestamp
205 # Use Age: 0 if local clock got turned back.
206 response["Age"] = max(0, max_age_seconds - remaining_seconds)
207
208 # hit, return cached response
209 request._cache_update_cache = False
210 return response
211
212
213 class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
214 """
215 Cache middleware that provides basic behavior for many simple sites.
216
217 Also used as the hook point for the cache decorator, which is generated
218 using the decorator-from-middleware utility.
219 """
220
221 def __init__(self, get_response, cache_timeout=None, page_timeout=None, **kwargs):
222 super().__init__(get_response)
223 # We need to differentiate between "provided, but using default value",
224 # and "not provided". If the value is provided using a default, then
225 # we fall back to system defaults. If it is not provided at all,
226 # we need to use middleware defaults.
227
228 try:
229 key_prefix = kwargs["key_prefix"]
230 if key_prefix is None:
231 key_prefix = ""
232 self.key_prefix = key_prefix
233 except KeyError:
234 pass
235 try:
236 cache_alias = kwargs["cache_alias"]
237 if cache_alias is None:
238 cache_alias = DEFAULT_CACHE_ALIAS
239 self.cache_alias = cache_alias
240 except KeyError:
241 pass
242
243 if cache_timeout is not None:
244 self.cache_timeout = cache_timeout
245 self.page_timeout = page_timeout