Naroju Naroju - 2 months ago 53
Python Question

Json parsing django rest framework

I want to parse incoming

data in django file

POST data:

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

Here is how I tried to read above incoming data with

class Fruits(APIView):

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

if request.method == "POST":

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

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

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

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


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

Answer 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 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"]