/usr/share/pyshared/django/middleware/gzip.py is in python-django 1.3.1-4ubuntu1.23.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import re
from django.utils.text import compress_string
from django.utils.text import compress_string, compress_sequence
from django.utils.cache import patch_vary_headers
re_accepts_gzip = re.compile(r'\bgzip\b')
class GZipMiddleware(object):
"""
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):
# The response object can tell us whether content is a string or an iterable
# It's not worth compressing non-OK or really short responses.
if response._is_string:
if response.status_code != 200 or len(response.content) < 200:
return response
patch_vary_headers(response, ('Accept-Encoding',))
# Avoid gzipping if we've already got a content-encoding.
if response.has_header('Content-Encoding'):
return response
# MSIE have issues with gzipped respones of various content types.
if "msie" in request.META.get('HTTP_USER_AGENT', '').lower():
ctype = response.get('Content-Type', '').lower()
if not ctype.startswith("text/") or "javascript" in ctype:
return response
ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
if not re_accepts_gzip.search(ae):
return response
# The response object can tell us whether content is a string or an iterable
if response._is_string:
response.content = compress_string(response.content)
response['Content-Length'] = str(len(response.content))
else:
# If the response content is iterable we don't know the length, so delete the header.
del response['Content-Length']
# Wrap the response content in a streaming gzip iterator (direct access to inner response._container)
response.content = compress_sequence(response._container)
response['Content-Encoding'] = 'gzip'
return response
|