| 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 |
# 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 |
|---|