Django: enable gzip compression in views

January 21, 2014

Last update: March 28, 2020

The problem

We want to speed up how our web application serves contents. One of the thing we can do is enabling resource compression.

A solution

Update: 05 Feb 2015 The previous approach is wrong: compression, chaching, etc. are business of web server. So, to speed up our pages we have to edit the VirtualHost (for Apache) configuration. Here the lines:

<VirtualHost *:80> # ... # set default charset AddDefaultCharset utf-8 # Cache settings - 1 week Header set Cache-Control "max-age=604800, public" # enable compression SetOutputFilter DEFLATE # ... </VirtualHost>

A wrong solution

One of the most valuable tricks, we can apply to our Django projects to improve speed, is to enable GZip compression. Of course, it is easy! See the example below.

from django.views.decorators.gzip import gzip_page @gzip_page def my_view(request): ...

References

  1. View decorators: GZip compression


Did you find this post useful? What about Buy Me A Coffee

A photo of Elia Contini
Written by
Elia Contini
Sardinian UX engineer and a Front-end web architect based in Switzerland. Marathoner, traveller, wannabe nature photographer.