使用请求库将JSON有效负载传递到django REST API时出现问题

uinbv5nw  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(90)

我开始使用Django REST API,并遵循This YouTube video
我的客户代码是:

import requests

endpoint = "http://127.0.0.1:8000/api"

get_response = requests.get(endpoint,params={"abc":123},json={'query' : 'HELLO WORLD!!'})
print(get_response.json()

我的API代码是:

from django.http import JsonResponse
import json

def api_home(request):
    body = request.body
    print(body)
    data = {}
    try:
        data = json.loads(body)
    except Exception as e:
        print(e)
    print(data) # returns {}
    dtat["content_type"] = request.content_type
    return JsonResponse(data)

这里的主体应该包含客户端发送的“JSON数据的字节串”,print(body)应该打印b'{'query' : 'HELLO WORLD!!'}',但我得到的结果是b'{}'和try中的异常Expecting value: line 1 column 1 (char 0):除外。JsonResponse将{"content_type": "text/plain"}返回给客户端,因为它应该是{"content_type" : "application/json"}
有人能帮我解决我做错了什么以及如何改正吗
修改代码后,谷歌解决方案结束了相同的异常。
一个二个一个一个

x7rlezfr

x7rlezfr1#

requests.get()没有json参数,我猜这只是在客户端代码中被忽略了,事实上,通常在GET请求的主体中包含任何数据是不常见的。
你可能会把它和requests.post()json参数搞混,我们总是在POST请求的主体中包含数据。
我建议大家跟随official Django tutorial学习Django,它是一个全栈的Web应用而不是API,但会比这个视频更准确。

相关问题