python - 无法访问请求中的值

标签 python django

我不明白如何从 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/

相关文章:

python - 数据未使用 python mysql.connector 存储在 mysql 中

django - 相对进口

python - 如何使用 django_graphene 解析 django 模型的自定义字段?

python - 将 JSON 值插入 mysql 但插入的是 0

python - 在 pandas 中,将散点图添加到线图上

python - 如何改进我的算法运行时间? cpoptimithe 不建议

python - 什么在第五行之后切片行

python - Django:关于设计具有不同字段的模型的建议

OSX 10.5 上的 Python 2.7 Virtualenv 路径问题

django - 如何以编程方式在另一个 View 中调用 Django Rest Framework View ?