【问题标题】:why does python requests.post accept json for data but not a dictionary为什么 python requests.post 接受 json 作为数据而不是字典
【发布时间】:2017-02-08 18:43:38
【问题描述】:

文档似乎表明我可以将 'data=' 作为字典传递,但除非我使用 json.dumps(),否则我会收到错误消息

options = {
    "deviceId":["4d51de64-2235-a465-3aee-5ec495b5b250"],
    "serviceName":"software_manager",
    "serviceVersion":"1.0",
    "actionName":"Dump Log Files" }

res = requests.post( req, data=json.dumps(options), auth=cred) 

如果我尝试将选项作为字典传递,它会失败。

res = requests.post( req, data=options, auth=cred) 

data=json.dumps(options) # This works
data=options             # this fails

为什么?我在文档中遗漏了什么吗?

【问题讨论】:

  • 失败如何?显示错误。
  • 你应该使用res = requests.post( req, json=options, auth=cred)
  • 您需要通过 POST 检查目的地所期望的媒体类型。它可能会失败,因为目的地只接受 json。
  • 谢谢! json= 有效,data= 无效。
  • 错误只是 status_code = 400

标签: python json python-requests


【解决方案1】:

requests.post()data 参数接受格式编码的数据(如果您将其传递给 dict)或作为原始字符串(这就是 json.dumps(options) 起作用的原因)。

为了传入一个非编码的字典,你应该使用.post()json参数。

【讨论】:

  • 谢谢。我错过了关于“表单编码”的部分...... http新手!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多