无法访问请求中的值

时间:2016-12-28 00:16:57

标签: python django

我不了解如何从我的Python API中访问POST请求中的值。

为什么我无法访问API请求中的值?我显然是在request.body中获取它们,但无法检索它们。

我尝试过以下方法:

request.POST['username']
request.POST.get('username')

我收到一条错误,指出 django.utils.datastructures.MultiValueDictKeyError:

这是request.body,它看起来根本不像JSON。

"{\n \"username\": \"TestUsername\",\n \"password\": \"TestPass\"\n}"

POST REQUEST

{
  "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'})

1 个答案:

答案 0 :(得分:3)

我觉得因为this.executeAsync.then(() => { // after while loop code }); private executeAsync(): Promise<void> { return new Promise((callback) => this.executeAsyncLoop(callback)); } private executeAsyncLoop(callback: () => void): void { myClass.executeScript.then((thisWasSuccessful: boolean) => { if(!thisWasSuccessful) executeAsyncLoop(callback); else callback(); }); } 标题为Content-Type,您首先需要将请求正文解析为JSON:

application/json

虽然我认为Django应该自动处理这个问题。如果它适合你,请告诉我!

编辑:看起来你正在使用Django REST Framework。如果是这样:使用import json body = json.loads(request.POST) 代替request.data访问您的数据。