【问题标题】:Python POST request can't find data attributePython POST 请求找不到数据属性
【发布时间】: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 对数据进行编码。

标签: python django post


【解决方案1】:

您不需要对您的data 进行 JSON 编码,因为您没有在视图中使用 JSON 做任何事情。只需将您的字典直接传递给data

response = requests.post(url, data=data, headers=headers)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2022-07-27
    • 2020-10-17
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多