在django中处理python post请求和响应中的json

时间:2016-04-27 09:23:19

标签: python json django python-2.7 request

我们正在尝试使用python中的请求包向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中获得预期的输出?

1 个答案:

答案 0 :(得分:1)

getlist用于key2。

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

但您可能会发现将数据作为JSON发送并访问json.loads(request.body)更容易。

相关问题