~canonical-django/canonical-django/project-template

« back to all changes in this revision

Viewing changes to trunk/python-packages/django/middleware/gzip.py

  • Committer: Matthew Nuzum
  • Date: 2008-11-13 05:46:03 UTC
  • Revision ID: matthew.nuzum@canonical.com-20081113054603-v0kvr6z6xyexvqt3
adding to version control

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import re
 
2
 
 
3
from django.utils.text import compress_string
 
4
from django.utils.cache import patch_vary_headers
 
5
 
 
6
re_accepts_gzip = re.compile(r'\bgzip\b')
 
7
 
 
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
 
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
        # 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
 
31
 
 
32
        ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
 
33
        if not re_accepts_gzip.search(ae):
 
34
            return response
 
35
 
 
36
        response.content = compress_string(response.content)
 
37
        response['Content-Encoding'] = 'gzip'
 
38
        response['Content-Length'] = str(len(response.content))
 
39
        return response