简体   繁体   English

在视图中获取 JSON 请求(使用 Django)

[英]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 being properly received:我正在尝试设置一个视图以接收来自 API 的 JSON 通知。我正在尝试弄清楚如何获取 JSON 数据,目前我以此为起点来查看请求是否被正确接收:

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

I know the JSON object is there because in the print request it shows:我知道 JSON object 在那里,因为在print request中它显示:

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.但是,POST 和 GET QueryDicts 都是空的。 How would I set up a view to receive the JSON object so I can process it?我将如何设置一个视图来接收 JSON object 以便我可以处理它? 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('')

On a function view, you can try this out.在 function 视图上,您可以尝试一下。

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对于使用 Django-Rest-Framework 构建的基于类的视图,您可以使用内置的JSONParser来获取 request.data 中的 JSON 数据

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)

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.我正在使用香草 django 版本 3.2.9。 I was struggling to retrieve data after making a post request with a json payload to a view.在向视图发出带有 json 有效负载的发布请求后,我正在努力检索数据。 After searching for a while, I finally found the json in request.body .找了一阵子,终于在request.body找到了json。

Note: request.body is of type bytes , you'll have to decode it to utf-8, my_json_as_bytes.decode('utf-8')注意: request.bodybytes类型,您必须将其解码为 utf-8, my_json_as_bytes.decode('utf-8')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM