http.py 1.5 KB

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