2005-10-09 08:55:08 +08:00
|
|
|
from django.utils.cache import patch_vary_headers
|
2015-11-07 23:12:37 +08:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2019-10-26 22:42:32 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.text import compress_sequence, compress_string
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
re_accepts_gzip = _lazy_re_compile(r'\bgzip\b')
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
class GZipMiddleware(MiddlewareMixin):
|
2005-10-09 08:55:08 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Compress content if the browser allows gzip compression.
|
|
|
|
Set the Vary header accordingly, so that caches will base their storage
|
2005-10-09 08:55:08 +08:00
|
|
|
on the Accept-Encoding header.
|
|
|
|
"""
|
|
|
|
def process_response(self, request, response):
|
2012-01-10 05:42:03 +08:00
|
|
|
# It's not worth attempting to compress really short responses.
|
2012-10-20 23:40:14 +08:00
|
|
|
if not response.streaming and len(response.content) < 200:
|
2007-08-12 20:29:25 +08:00
|
|
|
return response
|
|
|
|
|
2007-11-19 11:41:46 +08:00
|
|
|
# Avoid gzipping if we've already got a content-encoding.
|
|
|
|
if response.has_header('Content-Encoding'):
|
|
|
|
return response
|
|
|
|
|
2014-06-10 03:24:05 +08:00
|
|
|
patch_vary_headers(response, ('Accept-Encoding',))
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
|
|
|
|
if not re_accepts_gzip.search(ae):
|
|
|
|
return response
|
|
|
|
|
2012-10-20 23:40:14 +08:00
|
|
|
if response.streaming:
|
|
|
|
# Delete the `Content-Length` header for streaming content, because
|
|
|
|
# we won't know the compressed size until we stream it.
|
|
|
|
response.streaming_content = compress_sequence(response.streaming_content)
|
2020-07-14 19:32:24 +08:00
|
|
|
del response.headers['Content-Length']
|
2012-10-20 23:40:14 +08:00
|
|
|
else:
|
|
|
|
# Return the compressed content only if it's actually shorter.
|
|
|
|
compressed_content = compress_string(response.content)
|
|
|
|
if len(compressed_content) >= len(response.content):
|
|
|
|
return response
|
|
|
|
response.content = compressed_content
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['Content-Length'] = str(len(response.content))
|
2012-01-10 05:42:03 +08:00
|
|
|
|
2016-10-11 15:42:00 +08:00
|
|
|
# If there is a strong ETag, make it weak to fulfill the requirements
|
|
|
|
# of RFC 7232 section-2.1 while also allowing conditional request
|
|
|
|
# matches on ETags.
|
|
|
|
etag = response.get('ETag')
|
|
|
|
if etag and etag.startswith('"'):
|
2020-07-14 19:32:24 +08:00
|
|
|
response.headers['ETag'] = 'W/' + etag
|
|
|
|
response.headers['Content-Encoding'] = 'gzip'
|
2012-10-20 23:40:14 +08:00
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
return response
|