I was wondering: would it be possible to compress the response payload in Django REST?
At the moment, the response payloads are plain JSON data. However, there's quite a lot of data to bounce back and forth so I was wondering if compressing the data would help with the bandwidth issues.
HTTP response compression will most likely not be handled by Django but by your HTTP server using the gzip or deflate algorithms.
You just need to make sure your HTTP server is configured to compress HTTP Responses with Content-Type
header set to application/json
.
How to enable gzip compression for nginx: https://rtcamp.com/tutorials/nginx/enable-gzip/
The following worked for me.
I actually turned gzip on at the nginx level, not within Django or Django Rest Framework.
/etc/nginx/nginx.conf file:
http {
#... other settings ...#
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
}
This leaves the compressing up to the nginx server and as most modern browsers automatically know how to extract (uncompress) gzip compression, I didn't need to do anything on my client-side - even when receiving json data inside an Angular spa app.
My 1.3 MB JSON payload turned into about a 180 KB payload.
A pretty quick and fast way to save MB's of data.
If you are using the Django / DRF built-in web server rather than Apache or nginx, that uses its own WSGI server, so those methods won't work for you.
However, Django does have a built-in gzip middleware which you should be able to use, as described in these answers:
https://stackoverflow.com/a/1864377/2540707
https://stackoverflow.com/a/14821684/2540707
That being said, for production use you should be using a real web server rather than Django's built-in one.