2005-10-09 08:55:08 +08:00
|
|
|
import re
|
|
|
|
from django.utils.text import compress_string
|
|
|
|
from django.utils.cache import patch_vary_headers
|
|
|
|
|
|
|
|
re_accepts_gzip = re.compile(r'\bgzip\b')
|
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class GZipMiddleware(object):
|
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):
|
2007-08-12 20:29:25 +08:00
|
|
|
if response.status_code != 200 or len(response.content) < 200:
|
|
|
|
# Not worth compressing really short responses or 304 status
|
|
|
|
# responses, etc.
|
|
|
|
return response
|
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
patch_vary_headers(response, ('Accept-Encoding',))
|
2006-08-01 05:31:35 +08:00
|
|
|
|
|
|
|
# Avoid gzipping if we've already got a content-encoding or if the
|
|
|
|
# content-type is Javascript (silly IE...)
|
|
|
|
is_js = "javascript" in response.headers.get('Content-Type', '').lower()
|
|
|
|
if response.has_header('Content-Encoding') or is_js:
|
2005-10-09 08:55:08 +08:00
|
|
|
return response
|
|
|
|
|
|
|
|
ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
|
|
|
|
if not re_accepts_gzip.search(ae):
|
|
|
|
return response
|
|
|
|
|
|
|
|
response.content = compress_string(response.content)
|
|
|
|
response['Content-Encoding'] = 'gzip'
|
2006-11-23 04:31:09 +08:00
|
|
|
response['Content-Length'] = str(len(response.content))
|
2005-10-09 08:55:08 +08:00
|
|
|
return response
|