You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gzip.py 2.0KB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import re
  2. from django.utils.cache import patch_vary_headers
  3. from django.utils.deprecation import MiddlewareMixin
  4. from django.utils.text import compress_sequence, compress_string
  5. re_accepts_gzip = 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. def process_response(self, request, response):
  13. # It's not worth attempting to compress really short responses.
  14. if not response.streaming and len(response.content) < 200:
  15. return response
  16. # Avoid gzipping if we've already got a content-encoding.
  17. if response.has_header('Content-Encoding'):
  18. return response
  19. patch_vary_headers(response, ('Accept-Encoding',))
  20. ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
  21. if not re_accepts_gzip.search(ae):
  22. return response
  23. if response.streaming:
  24. # Delete the `Content-Length` header for streaming content, because
  25. # we won't know the compressed size until we stream it.
  26. response.streaming_content = compress_sequence(response.streaming_content)
  27. del response['Content-Length']
  28. else:
  29. # Return the compressed content only if it's actually shorter.
  30. compressed_content = compress_string(response.content)
  31. if len(compressed_content) >= len(response.content):
  32. return response
  33. response.content = compressed_content
  34. response['Content-Length'] = str(len(response.content))
  35. # If there is a strong ETag, make it weak to fulfill the requirements
  36. # of RFC 7232 section-2.1 while also allowing conditional request
  37. # matches on ETags.
  38. etag = response.get('ETag')
  39. if etag and etag.startswith('"'):
  40. response['ETag'] = 'W/' + etag
  41. response['Content-Encoding'] = 'gzip'
  42. return response