Json解析Django Rest框架 [英] Json parsing django rest framework

查看:69
本文介绍了Json解析Django Rest框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析django views.py文件中的传入POST数据

I want to parse incoming POST data in django views.py file

POST数据:

{
"number" : "17386372",
"data" : ["banana","apple","grapes" ]  
}

这是我尝试使用request

views.py

class Fruits(APIView):

def post(self, request, format=None):

   if request.method == "POST":

        number = request.data.get('number')
        fruits_data = json.loads(request.body)

        if number not in [None, '', ' ']:
            try:

                response = {"return": "OK","data":fruits_data['data']}
                return Response(response)
            except:
                return Response({"return": "NOT OK"})
        else:
            return Response({"return": "NOT OK"})

    else:
        return Response({"return": "NOT OK"})

错误:

You cannot access body after reading from request's data stream

推荐答案

request.data和request.body是两种机制,它们读取原始的HTTP请求并以适合于python的格式构造数据.环境.这里的问题是您同时使用它们两者.因此,通过request.data调用已经读取了http连接的输入流.现在request.body也尝试访问相同的流,该流现在不包含任何数据.因此,它引发了错误.

request.data and request.body are the two mechanisms, which reads the raw http request and construct data in a format, that is suitable to be used in python environment. Here the problem is that you are using both of them simultaneously. Thus, the inputstream of http connection is already read, by request.data call. Now request.body also tries to access the same stream, which doesn't contain now any data. Thus, it's throwing an error.

对您来说,我认为以下代码将起作用:

For you, I think following code will work :

fruits_data = json.loads(request.body)
number = fruits_data["number"]

这篇关于Json解析Django Rest框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆