Fixed #8516: Corrected typos in UK localflavor documentation
[django.git] / django / middleware / gzip.py
blob3b849801da46b880abd69d16b3220e41d835c445
1 import re
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):
9 """
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.
13 """
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:
17 return response
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'):
23 return response
25 # Older versions of IE have issues with gzipped pages containing either
26 # Javascript and PDF.
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":
30 return response
32 ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
33 if not re_accepts_gzip.search(ae):
34 return response
36 response.content = compress_string(response.content)
37 response['Content-Encoding'] = 'gzip'
38 response['Content-Length'] = str(len(response.content))
39 return response