blob: e44d59a9604a48fd650a02268f4efcc34cf9b65b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
from django.middleware import MiddlewareMixin
from django.utils.cache import get_conditional_response, set_response_etag
from django.utils.http import parse_http_date_safe, split_directive_names
class ConditionalGetMiddleware(MiddlewareMixin):
"""
Handle conditional GET operations. If the response has an ETag or
Last-Modified header and the request has If-None-Match or
If-Modified-Since, replace the response with HttpNotModified. Add an ETag
header if needed.
"""
def process_response(self, request, response):
# It's too late to prevent an unsafe request with a 412 response, and
# for a HEAD request, the response body is always empty so computing
# an accurate ETag isn't possible.
if request.method != "GET":
return response
if self.needs_etag(response) and not response.has_header("ETag"):
set_response_etag(response)
etag = response.get("ETag")
last_modified = response.get("Last-Modified")
last_modified = last_modified and parse_http_date_safe(last_modified)
if etag or last_modified:
return get_conditional_response(
request,
etag=etag,
last_modified=last_modified,
response=response,
)
return response
def needs_etag(self, response):
"""Return True if an ETag header should be added to response."""
directives = split_directive_names(response.get("Cache-Control", ""))
return "no-store" not in directives
|