【发布时间】:2015-06-18 13:58:51
【问题描述】:
我正在尝试用 Python 向我的 Django REST API 写入一个 POST 请求,但它似乎在请求的数据部分中找不到属性。这是处理请求的函数:
def post(self, request, id, format=None):
obj = self.get_object_or_404(id)
operation = request.POST.get('operation', None)
if operation == None:
print "Operation was none, uh oh."
return Response()
else:
print "It worked!"
return Response()
现在这是 jquery 中的 POST ajax 调用。这个有效。 (打印“它成功了!”)
$.ajax({
method: 'POST',
beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Token ' + token)},
url: url,
data: {
'operation':-1,
},
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
现在这是 Python 中的 POST 调用,或者我的尝试。 “url”和“token”变量完全一样:
import json
import requests
url = <Same URL as above>
token = <same token as above>
data = {
'operation' : -1,
}
headers = {
"Authorization": "Token " + token,
}
response = requests.post(url, data=json.dumps(data), headers=headers)
此 python 请求不起作用 - 应用程序 api 打印“操作没有,呃哦。”为什么会发生这种情况?我没有在请求中正确传递我的数据参数吗?
编辑:已解决。不要对数据调用json_dumps,直接传入即可。
【问题讨论】:
-
你为什么要
json.dumps(data)?尝试通过data=data... -
啊!谢谢,那行得通。我这样做是因为其他一些教程说您需要在发出发布请求之前通过 json 对数据进行编码。