Naroju Naroju - 27 days ago 32
Python Question

Json parsing django rest framework

I want to parse incoming

POST
data in django views.py file

POST data:

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


Here is how I tried to read above incoming data with
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"})


ERROR:

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

Answer

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