2016-04-27 132 views
0

我们试图使用python中的请求包发送对django api的post请求。在python中处理json post请求和在django中响应

请求:

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预期的输出?

回答

1

对于key2使用getlist

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

但你可能会发现更容易地将数据发送的JSON和访问json.loads(request.body)

+0

在key2中使用getlist给出[u'a',u'c'] 而不是整个字典 – user3351750