PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 4ms RepoModel.GetById 36ms app.codeStats 0ms

/django/middleware/gzip.py

https://code.google.com/p/mango-py/
Python | 38 lines | 24 code | 6 blank | 8 comment | 5 complexity | 736e15cec955c7c22f73c69b28d706b5 MD5 | raw file
 1import re
 2
 3from django.utils.text import compress_string
 4from django.utils.cache import patch_vary_headers
 5
 6re_accepts_gzip = re.compile(r'\bgzip\b')
 7
 8class 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
18
19        patch_vary_headers(response, ('Accept-Encoding',))
20
21        # Avoid gzipping if we've already got a content-encoding.
22        if response.has_header('Content-Encoding'):
23            return response
24
25        # MSIE have issues with gzipped respones of various content types.
26        if "msie" in request.META.get('HTTP_USER_AGENT', '').lower():
27            ctype = response.get('Content-Type', '').lower()
28            if not ctype.startswith("text/") or "javascript" in ctype:
29                return response
30
31        ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
32        if not re_accepts_gzip.search(ae):
33            return response
34
35        response.content = compress_string(response.content)
36        response['Content-Encoding'] = 'gzip'
37        response['Content-Length'] = str(len(response.content))
38        return response