Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 627
Naroju Avatar asked Nov 25 '25 10:11

Naroju


2 Answers

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"]
like image 183
Mangu Singh Rajpurohit Avatar answered Nov 27 '25 23:11

Mangu Singh Rajpurohit


The Django json parser does this already for you:

from rest_framework import parsers

class Fruits(APIView):
    parser_classes = (parsers.JSONParser,)

    def post(self, request, format=None):
        number = request.data['number']
        fruits = request.data['data']

If the Content-Type of your http request is already set properly to application/json you do not even need to specify the parser.

like image 22
romor Avatar answered Nov 28 '25 00:11

romor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!