Django rest framework, install Content-Encoding api response for gzip

I am working on a django project that acts as a distribution server to another server when they request some specific data via and api call, this data is in JSON form and very large. So I thought I could set my DRF APIView response to handle the outputted JSON response with a gzip set for Content-Encoding to reduce the size of the content when consumed by other servers.

My application is currently running on gunicorn with nginx on the front as proxy.

+3


source to share


1 answer


Django has gzip middleware built in .

If you are using django version <= 1.10 in settings.py

:

MIDDLEWARE_CLASSES = [
    'django.middleware.gzip.GZipMiddleware',
    ...
]

      

If you are using django version> 1.10:



MIDDLEWARE = [
    'django.middleware.gzip.GZipMiddleware',
    ...
]

      

This middleware must be placed before any other middleware that must read or write the response body for compression to occur later.

Why? Because for an incoming request, django handles the request using middlewares from top to bottom as defined in your settings. For outbound responses, middlewares are named from bottom to top.

Thus, declaring middleware gzip

as the first middleware will allow the incoming request to be decompressed for other intermediaries to read; and the outgoing response will be compressed just before leaving so that it does not interfere with the operations of other intermediaries.

+5


source







All Articles