2015-06-05 21:26:48 +08:00
|
|
|
from django.utils.cache import get_conditional_response
|
2015-11-07 23:12:37 +08:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2016-01-05 15:09:10 +08:00
|
|
|
from django.utils.http import http_date, parse_http_date_safe, unquote_etag
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
class ConditionalGetMiddleware(MiddlewareMixin):
|
2005-10-09 08:55:08 +08:00
|
|
|
"""
|
2014-05-29 08:39:14 +08:00
|
|
|
Handles conditional GET operations. If the response has an ETag or
|
2005-10-09 08:55:08 +08:00
|
|
|
Last-Modified header, and the request has If-None-Match or
|
|
|
|
If-Modified-Since, the response is replaced by an HttpNotModified.
|
|
|
|
|
|
|
|
Also sets the Date and Content-Length response-headers.
|
|
|
|
"""
|
|
|
|
def process_response(self, request, response):
|
2007-10-31 11:59:40 +08:00
|
|
|
response['Date'] = http_date()
|
2012-10-20 23:40:14 +08:00
|
|
|
if not response.streaming and not response.has_header('Content-Length'):
|
2005-10-09 08:55:08 +08:00
|
|
|
response['Content-Length'] = str(len(response.content))
|
|
|
|
|
2015-06-05 21:26:48 +08: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 08:55:08 +08:00
|
|
|
|
2015-06-05 21:26:48 +08:00
|
|
|
if etag or last_modified:
|
|
|
|
return get_conditional_response(
|
|
|
|
request,
|
2016-01-05 15:09:10 +08:00
|
|
|
etag=unquote_etag(etag),
|
2015-06-05 21:26:48 +08:00
|
|
|
last_modified=last_modified,
|
|
|
|
response=response,
|
|
|
|
)
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
return response
|