2016-04-03 10:15:10 +00:00
|
|
|
from django.utils.cache import (
|
|
|
|
cc_delim_re, get_conditional_response, set_response_etag,
|
|
|
|
)
|
2015-11-07 15:12:37 +00:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2016-10-14 12:02:19 +00:00
|
|
|
from django.utils.http import parse_http_date_safe
|
2005-10-09 00:55:08 +00:00
|
|
|
|
2013-11-02 20:12:09 +00:00
|
|
|
|
2015-11-07 15:12:37 +00:00
|
|
|
class ConditionalGetMiddleware(MiddlewareMixin):
|
2005-10-09 00:55:08 +00:00
|
|
|
"""
|
2014-05-29 00:39:14 +00:00
|
|
|
Handles conditional GET operations. If the response has an ETag or
|
2005-10-09 00:55:08 +00:00
|
|
|
Last-Modified header, and the request has If-None-Match or
|
2016-04-03 10:15:10 +00:00
|
|
|
If-Modified-Since, the response is replaced by an HttpNotModified. An ETag
|
|
|
|
header is added if needed.
|
2005-10-09 00:55:08 +00:00
|
|
|
|
2016-10-14 12:02:19 +00:00
|
|
|
Also sets the Content-Length response-header.
|
2005-10-09 00:55:08 +00:00
|
|
|
"""
|
|
|
|
def process_response(self, request, response):
|
2012-10-20 15:40:14 +00:00
|
|
|
if not response.streaming and not response.has_header('Content-Length'):
|
2005-10-09 00:55:08 +00:00
|
|
|
response['Content-Length'] = str(len(response.content))
|
|
|
|
|
2016-04-03 10:15:10 +00:00
|
|
|
if self.needs_etag(response) and not response.has_header('ETag'):
|
|
|
|
set_response_etag(response)
|
|
|
|
|
2015-06-05 13:26:48 +00:00
|
|
|
etag = response.get('ETag')
|
|
|
|
last_modified = response.get('Last-Modified')
|
|
|
|
if last_modified:
|
|
|
|
last_modified = parse_http_date_safe(last_modified)
|
2005-10-09 00:55:08 +00:00
|
|
|
|
2015-06-05 13:26:48 +00:00
|
|
|
if etag or last_modified:
|
|
|
|
return get_conditional_response(
|
|
|
|
request,
|
2016-09-01 13:32:20 +00:00
|
|
|
etag=etag,
|
2015-06-05 13:26:48 +00:00
|
|
|
last_modified=last_modified,
|
|
|
|
response=response,
|
|
|
|
)
|
2005-10-09 00:55:08 +00:00
|
|
|
|
|
|
|
return response
|
2016-04-03 10:15:10 +00:00
|
|
|
|
|
|
|
def needs_etag(self, response):
|
|
|
|
"""
|
|
|
|
Return True if an ETag header should be added to response.
|
|
|
|
"""
|
|
|
|
cache_control_headers = cc_delim_re.split(response.get('Cache-Control', ''))
|
|
|
|
return all(header.lower() != 'no-store' for header in cache_control_headers)
|