2011-03-01 22:28:06 +08:00
|
|
|
from django.utils.http import http_date, parse_http_date_safe
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class ConditionalGetMiddleware(object):
|
2005-10-09 08:55:08 +08:00
|
|
|
"""
|
|
|
|
Handles conditional GET operations. If the response has a ETag or
|
|
|
|
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()
|
2005-10-09 08:55:08 +08:00
|
|
|
if not response.has_header('Content-Length'):
|
|
|
|
response['Content-Length'] = str(len(response.content))
|
|
|
|
|
|
|
|
if response.has_header('ETag'):
|
2011-03-01 22:28:06 +08:00
|
|
|
if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
|
2005-10-09 08:55:08 +08:00
|
|
|
if if_none_match == response['ETag']:
|
2007-11-11 11:55:44 +08:00
|
|
|
# Setting the status is enough here. The response handling path
|
|
|
|
# automatically removes content for this status code (in
|
|
|
|
# http.conditional_content_removal()).
|
2008-06-30 15:03:58 +08:00
|
|
|
response.status_code = 304
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
if response.has_header('Last-Modified'):
|
2011-03-01 22:28:06 +08:00
|
|
|
if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
|
|
|
|
if if_modified_since is not None:
|
|
|
|
if_modified_since = parse_http_date_safe(if_modified_since)
|
|
|
|
if if_modified_since is not None:
|
|
|
|
last_modified = parse_http_date_safe(response['Last-Modified'])
|
|
|
|
if last_modified is not None and last_modified <= if_modified_since:
|
|
|
|
# Setting the status code is enough here (same reasons as
|
|
|
|
# above).
|
|
|
|
response.status_code = 304
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
return response
|