/django/middleware/http.py

https://code.google.com/p/mango-py/ · Python · 36 lines · 20 code · 4 blank · 12 comment · 8 complexity · 7e8f5beba78d8959ad64e9ab7e870729 MD5 · raw file

  1. from django.core.exceptions import MiddlewareNotUsed
  2. from django.utils.http import http_date, parse_http_date_safe
  3. class ConditionalGetMiddleware(object):
  4. """
  5. Handles conditional GET operations. If the response has a ETag or
  6. Last-Modified header, and the request has If-None-Match or
  7. If-Modified-Since, the response is replaced by an HttpNotModified.
  8. Also sets the Date and Content-Length response-headers.
  9. """
  10. def process_response(self, request, response):
  11. response['Date'] = http_date()
  12. if not response.has_header('Content-Length'):
  13. response['Content-Length'] = str(len(response.content))
  14. if response.has_header('ETag'):
  15. if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
  16. if if_none_match == response['ETag']:
  17. # Setting the status is enough here. The response handling path
  18. # automatically removes content for this status code (in
  19. # http.conditional_content_removal()).
  20. response.status_code = 304
  21. if response.has_header('Last-Modified'):
  22. if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
  23. if if_modified_since is not None:
  24. if_modified_since = parse_http_date_safe(if_modified_since)
  25. if if_modified_since is not None:
  26. last_modified = parse_http_date_safe(response['Last-Modified'])
  27. if last_modified is not None and last_modified <= if_modified_since:
  28. # Setting the status code is enough here (same reasons as
  29. # above).
  30. response.status_code = 304
  31. return response