Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework, set the api response Content-Encoding to gzip

Am working on django project, that act as a distribution server to other server when they request for some certain data through and api call, this data is in form of JSON and is very large. So i was thinking is there any way i can set my DRF APIView response to serves the outputted JSON response with gzip set for the Content-Encoding so as to reduce the size of the content, when consuming by the other servers.

Currently my application is running on gunicorn with nginx on the front as a proxy.

like image 495
pitaside Avatar asked Apr 24 '17 13:04

pitaside


People also ask

How do I change content type in Django REST framework?

Browsable API class MultiPartParser(BaseParser): """ Parser for multipart form data, which may include file data. """ media_type = 'multipart/form-data' def parse(self, stream, media_type=None, parser_context=None): ... encoding = parser_context. get('encoding', settings.

What is Restapi in Django?

Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: The Web browsable API is a huge usability win for your developers. Authentication policies including packages for OAuth1a and OAuth2.

What is Django REST framework browsable API?

The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header.

Can we use Django for REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.


1 Answers

Django has a built-in gzip middleware.

If you're using django version <= 1.10 , in your settings.py:

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

If you're using django version > 1.10:

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

This middleware should be placed before any other middleware that need to read or write the response body so that compression happens afterward.

Why? Because for an incoming request django processes the request using middlewares from top to bottom as defined in your settings. For out going response middlewares are called bottom to top.

So declaring gzip middleware as the first middleware will enable the incoming request to be decompressed to be read by other middlewares ; and the outgoing response will be compressed just before leaving, so that it does not interfere with the operations of other middlewares.

like image 87
xssChauhan Avatar answered Sep 28 '22 16:09

xssChauhan