5

我在 Windows 中使用 curl exe 与我的 Django 后端进行通信。

以下是正在使用的命令。

curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"uid\":12,\"token\":\"asdert\"}" http://localhost:8000/restapi/v1/foo/

现在这会以错误的格式给出数据。即在视图中,帖子显示此数据打印请求。POST

{"{\"uid\":12,\"access_token\":\"asdert\"}": [""]}

发布 json 数据的正确方法是什么?

编辑:

我尝试了其他几种方法,例如我正在尝试使用 http://slumber.in/与我的 rest api 进行通信。

即使在这里得到与上述相同的结果。

import slumber
api = slumber.API("http://localhost/restapi/v1/"
api.foo.post({"uid":"100"})

视图打印request.POST的摘录

 {u'{"uid": "100"}': [u'']}

PS - curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "uid=12&token=asdert" http://localhost:8000/restapi/v1/foo/

这行得通。但这不是 Json 格式。

4

1 回答 1

9

我用http://httpbin.org/post尝试了你的命令,效果很好。

现在,您的问题是您应该从

request.raw_post_data

而不是request.POST.

(或者,如果您使用的是 Django 1.4+,请改用request.bodyrequest.raw_post_data弃用的版本)


详细代码应该是这样的:

import json

if request.method == "POST":
    data = json.loads(request.raw_post_data)
    print data
于 2012-10-21T09:40:27.370 回答