简体   繁体   English

无法使用 Django Rest 框架发送压缩的 gzip 数据

[英]unable to Send compressed gzip data using Django Rest framework

I am sending JSON file in Django Rest APIView framework.我正在 Django Rest APIView 框架中发送 JSON 文件。 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 Django rest框架,设置api响应Content-Encoding为gzip

MIDDLEWARE = [ 'django.middleware.gzip.GZipMiddleware', ... ]中间件 = [ 'django.middleware.gzip.GZipMiddleware', ... ]

Trying to call from Postman and it is showing below error.尝试从 Postman 呼叫,但显示以下错误。

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 1 的字节 0x8b:起始字节无效。 500, Internal server error. 500内部服务器错误。

Is there a way I can setup Accept-Encoding somewhere.有没有办法可以在某处设置接受编码。 I cannot figureout this.我无法弄清楚这一点。 Please note postman has Accept-Encoding to gzip, deflate, br请注意邮递员已接受编码为gzip、deflate、br

Could you please answer what is the problem?你能回答一下是什么问题吗?

Thanks谢谢

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 ):只需将settings.py的中间件称为列表中的第一个( 如您的链接中所述):

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.请确保在您的请求中包含Accept-Encoding: gzip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM