3
from django.utils.text import compress_string
4
from django.utils.cache import patch_vary_headers
6
re_accepts_gzip = re.compile(r'\bgzip\b')
8
class GZipMiddleware(object):
10
This middleware compresses content if the browser allows gzip compression.
11
It sets the Vary header accordingly, so that caches will base their storage
12
on the Accept-Encoding header.
14
def process_response(self, request, response):
15
# It's not worth compressing non-OK or really short responses.
16
if response.status_code != 200 or len(response.content) < 200:
19
patch_vary_headers(response, ('Accept-Encoding',))
21
# Avoid gzipping if we've already got a content-encoding.
22
if response.has_header('Content-Encoding'):
25
# Older versions of IE have issues with gzipped pages containing either
27
if "msie" in request.META.get('HTTP_USER_AGENT', '').lower():
28
ctype = response.get('Content-Type', '').lower()
29
if "javascript" in ctype or ctype == "application/pdf":
32
ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
33
if not re_accepts_gzip.search(ae):
36
response.content = compress_string(response.content)
37
response['Content-Encoding'] = 'gzip'
38
response['Content-Length'] = str(len(response.content))