I'm trying to serve a gzipped version of a text/html page in Django, but Firefox is telling me there's a content encoding error.
NOTES:
- I realize this is not a best practice and I'm most likely going to use mod_gzip. This is just a learning exercise to understand what's going on.
- I know about the Django gzip middleware-- it has problems with binary files.
Here's my code:
rendered_page = zlib.compress(template.render(context).encode('utf-8'))
response = HttpResponse(rendered_page)
response['Content-Encoding'] = 'gzip'
response['Content-Length'] = len(rendered_page)
return response
Am I missing something here? Is it possible that the content length is wrong? Are there additional headers I'm missing?
Thanks.
zlib
is a bit too low-level for this purpose. Here's how the GZip middleware itself does it (see compress_string in django.utils.text.py):GZip uses zlib, but on its own zlib produces content that's improperly encoded for a browser seeing 'gzip' as the content encoding. Hope that helps!
For the sake of others finding this question and who are using nginx, this SO worked for me:
https://stackoverflow.com/a/41820704/4533488
Basically turning gzip on in the /etc/nginx/nginx.conf file did all the compression handling for me. On the client-side, most modern browsers automatically handle extracting (uncompressing) the data when receiving it - sweet!
Here is the nginx.conf file settings:
You could also simply use django's gzip middleware:
Either by enabling the middleware in settings.py by adding:
Or do it before you return a particular response. In your views.py, dec would be the handler for a certain url
If you need it for a single page and you are using class based views, use this:
Then in your actual view:
If you're gzipping single page, not for all pages, you can use gzip_page decorator instead of GzipMiddleware.
Reference here: https://docs.djangoproject.com/en/1.4/topics/http/decorators/#module-django.views.decorators.gzip
If you compress your data with
zlib
, you have to setContent-Encoding
todeflate
, notgzip
.