David Cramer's Blog

Improving GZipMiddleware in Django

One issue we had come up over at iBegin lately, is the fact that GZipMiddleware tries to encode ALL responses (with a few minor exceptions). In our cases, we sometimes stream actual binary files over the response. Doing this with the standard middleware causes a unicode error as it’s trying to encode all of the information before gzipping it.

So to fix this, we simply created a slightly improved middleware to handle the content types a bit better:

1
2
3
4
5
6
7
8
9
10
11
from django.middleware.gzip import GZipMiddleware

<p>class ImprovedGZipMiddleware(GZipMiddleware):
"""Will GZip the content if it's not text/*, xml, or a javascript content type."""
def process_response(self, request, response):
ctype = response.get('Content-Type', '').lower()
if not ctype.startswith('text/')\
or 'javascript' in ctype\
or 'xml' in ctype:
return response
return super(ImprovedGZipMiddleware, self).process_response(request, response)