gzip.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from django.utils.cache import patch_vary_headers
  2. from django.utils.deprecation import MiddlewareMixin
  3. from django.utils.regex_helper import _lazy_re_compile
  4. from django.utils.text import compress_sequence, compress_string
  5. re_accepts_gzip = _lazy_re_compile(r"\bgzip\b")
  6. class GZipMiddleware(MiddlewareMixin):
  7. """
  8. Compress content if the browser allows gzip compression.
  9. Set the Vary header accordingly, so that caches will base their storage
  10. on the Accept-Encoding header.
  11. """
  12. max_random_bytes = 100
  13. def process_response(self, request, response):
  14. # It's not worth attempting to compress really short responses.
  15. if not response.streaming and len(response.content) < 200:
  16. return response
  17. # Avoid gzipping if we've already got a content-encoding.
  18. if response.has_header("Content-Encoding"):
  19. return response
  20. patch_vary_headers(response, ("Accept-Encoding",))
  21. ae = request.META.get("HTTP_ACCEPT_ENCODING", "")
  22. if not re_accepts_gzip.search(ae):
  23. return response
  24. if response.streaming:
  25. if response.is_async:
  26. # pull to lexical scope to capture fixed reference in case
  27. # streaming_content is set again later.
  28. orignal_iterator = response.streaming_content
  29. async def gzip_wrapper():
  30. async for chunk in orignal_iterator:
  31. yield compress_string(
  32. chunk,
  33. max_random_bytes=self.max_random_bytes,
  34. )
  35. response.streaming_content = gzip_wrapper()
  36. else:
  37. response.streaming_content = compress_sequence(
  38. response.streaming_content,
  39. max_random_bytes=self.max_random_bytes,
  40. )
  41. # Delete the `Content-Length` header for streaming content, because
  42. # we won't know the compressed size until we stream it.
  43. del response.headers["Content-Length"]
  44. else:
  45. # Return the compressed content only if it's actually shorter.
  46. compressed_content = compress_string(
  47. response.content,
  48. max_random_bytes=self.max_random_bytes,
  49. )
  50. if len(compressed_content) >= len(response.content):
  51. return response
  52. response.content = compressed_content
  53. response.headers["Content-Length"] = str(len(response.content))
  54. # If there is a strong ETag, make it weak to fulfill the requirements
  55. # of RFC 9110 Section 8.8.1 while also allowing conditional request
  56. # matches on ETags.
  57. etag = response.get("ETag")
  58. if etag and etag.startswith('"'):
  59. response.headers["ETag"] = "W/" + etag
  60. response.headers["Content-Encoding"] = "gzip"
  61. return response