簡體   English   中英

在Django中處理python post請求和響應中的json

[英]handle json in python post request and response in django

我們正在嘗試使用python中的request包向django api發出發布請求。

請求:

d = {"key1":"123", "key2":[{"a":"b"},{"c":"d"}]}

response = requests.post("http://127.0.0.1:8000/api/postapi/",data=d)

在服務器端,我們嘗試使用以下代碼獲取參數。

def handle_post(request):
    if request.method == 'POST':
        key1 = request.POST.get('key1', '')
        key2 = request.POST.get('key2', '')
        print key1,type(key1)
        print key2,type(key2)
        return JsonResponse({'result': 'success'}, status=200)

我正在嘗試獲取key1和key2中的值。

預期產量:

123,<type 'unicode'>
[{"a":"b"},{"c":"d"}], <type 'list'>

實際輸出:

123 <type 'unicode'>
c <type 'unicode'>

我們如何在django中獲得預期的輸出?

getlist用於key2。

key2 = request.POST.getlist('key2', '')

但是您可能會發現將數據作為JSON發送並訪問json.loads(request.body)更加容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM