2005-10-09 08:55:08 +08:00
|
|
|
import re
|
2007-11-19 11:41:46 +08:00
|
|
|
|
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
|
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
|
|
|
|
|
|
|
re_accepts_gzip = re.compile(r'\bgzip\b')
|
|
|
|
|
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
|
|
|
"""
|
|
|
|
This middleware compresses content if the browser allows gzip compression.
|
|
|
|
It sets the Vary header accordingly, so that caches will base their storage
|
|
|
|
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)
|
|
|
|
del response['Content-Length']
|
|
|
|
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
|
|
|
|
response['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('"'):
|
|
|
|
response['ETag'] = 'W/' + etag
|
2005-10-09 08:55:08 +08:00
|
|
|
response['Content-Encoding'] = 'gzip'
|
2012-10-20 23:40:14 +08:00
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
return response
|