我不明白如何从 Python API 中访问 POST 请求中的值。
为什么我无法访问 API 请求中的值?我显然在 request.body 中获取了它们,但无法检索它们。
我尝试过以下方法:
request.POST['username']
request.POST.get('username')
我收到一条错误,指出 django.utils.datastructs.MultiValueDictKeyError:
这是 request.body,它看起来根本不像 JSON。
"{\n \"username\": \"TestUsername\",\n \"password\": \"TestPass\"\n}"
发布请求
{
"username": "TestUsername",
"password": "TestPass"
}
标题
Accept: application/json
Content-Type: application/json
查看
@csrf_exempt
@api_view(['POST'])
def create(request):
user = User()
if 'username' in request.POST and 'password' in request.POST:
user.username = request.POST['username']
user.set_password(request.POST['password'])
user.save()
return Response({'Status' : 'Complete'})
else:
return Response({'Status': 'Incomplete'})
最佳答案
在我看来,因为您的 Content-Type
header 是 application/json
,所以您首先需要将请求正文解析为 JSON:
import json
body = json.loads(request.POST)
尽管我认为 Django 应该自动处理这个问题。让我知道它是否适合您!
编辑:看起来您正在使用 Django REST Framework。如果是这样:使用 request.data
而不是 request.POST['key']
访问您的数据。
关于python - 无法访问请求中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353797/