Chakra
Chakra

Reputation: 746

unable to Send compressed gzip data using Django Rest framework

I am sending JSON file in Django Rest APIView framework. I want to reduce the size of the file. Implemented below code but Receving below error:

@api_view(['GET','POST'])
def myMethod(request):

   from rest_framework.response import Response

   if request.method == 'POST':
       import gzip
       # ****Some code lines here to generated small json***
       myJson = json.dumps(parsed, indent=4)
       compressedContent = gzip.compress(myJson.encode('utf-8'), 5)  # compressedContent is byte format
       return Response(compressedContent, status=status.HTTP_200_OK)

As mentioned in this link, I implemented middleware too. Django rest framework, set the api response Content-Encoding to gzip

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

Trying to call from Postman and it is showing below error.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. 500, Internal server error.

Is there a way I can setup Accept-Encoding somewhere. I cannot figureout this. Please note postman has Accept-Encoding to gzip, deflate, br

Could you please answer what is the problem?

Thanks

Upvotes: 3

Views: 2046

Answers (1)

Carlos Massucci
Carlos Massucci

Reputation: 88

Well, I was having the same issue.

It is easier than expected. Just call the middleware in settings.py as the first in the list (as explained in your link):

MIDDLEWARE = [
    'django.middleware.gzip.GZipMiddleware', #This one does the job
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

After that the middleware will handle the request compression. So there is no need to compress it in the code neither to declare new headers:

@api_view(['GET','POST'])
def myMethod(request):

   from rest_framework.response import Response

   if request.method == 'POST':
       myJson = json.dumps(parsed, indent=4)
       return Response(myJson , status=status.HTTP_200_OK)

Just be sure to have Accept-Encoding: gzip in your request.

Upvotes: 5

Related Questions