开发者

Getting a JSON request in a view (using Django)

I am trying to set up a view to received a JSON notification from an API. I'm trying to figure out how to get the JSON data, and I currently have this as a starting point to see that the request is b开发者_运维知识库eing properly received:

def api_response(request):
    print request
    return HttpResponse('')

I know the JSON object is there because in the print request it shows:

META:{'CONTENT_LENGTH': '178',
[Fri Sep 09 16:42:27 2011] [error]  'CONTENT_TYPE': 'application/json',

However, both of the POST and GET QueryDicts are empty. How would I set up a view to receive the JSON object so I can process it? Thank you.


This is how I did it:

def api_response(request):
    try:
        data=json.loads(request.raw_post_data)
        label=data['label']
        url=data['url']
        print label, url
    except:
        print 'nope'
    return HttpResponse('')


I'm going to post an answer to this since it is the first thing I found when I searched my question on google. I am using vanilla django version 3.2.9. I was struggling to retrieve data after making a post request with a json payload to a view. After searching for a while, I finally found the json in request.body.

Note: request.body is of type bytes, you'll have to decode it to utf-8, my_json_as_bytes.decode('utf-8') or, if you want a dictionary, you can just use json.load(request.body) to decode directly.


On a function view, you can try this out.

dp = json.dumps(request.data)
contact = json.loads(dp)
print(contact['first_name'])


For Class-Based Views built Using Django-Rest-Framework, you can use built-in JSONParser to get JSON data in request.data

from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

class MyOveridingView(APIView):
    parser_classes = [JSONParser]

class MyActualView(MyOveridingView):

    def post(self, request, *args, **kwargs):
        request_json = request.data
        return JsonResponse(data=request_json, status=200)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜