2016-12-28 66 views
2

我不理解如何從我的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請求

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

HEADERS

Accept: application/json 
Content-Type: application/json 

VIEW

@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'}) 
+0

您能否包含MultiValueKeyDict錯誤的堆棧跟蹤? –

回答

3

在我看來,因爲你Content-Type頭是application/json,首先需要解析請求體爲JSON:

import json 

body = json.loads(request.POST) 

雖然我認爲應該Django的自動處理這個問題。讓我知道它是否適合你!

編輯:看起來像你使用Django REST框架。如果是這樣:使用request.data而不是request.POST['key']訪問您的數據。

+0

你真棒。我沒有意識到我正在使用特殊版本的請求。我認爲這只是一個標準的請求對象,因爲我沒有導入任何特定的情況。我對Python仍然很陌生。 –

相關問題