【问题标题】:How to pass a nested dictionary as a header in python-requests?如何在 python-requests 中将嵌套字典作为标头传递?
【发布时间】:2020-03-23 17:10:48
【问题描述】:

我的标题格式如下

import requests

header = {
          "content-type": "application/json",
          "a": {"b": "b_value"},
          "some_param": {"some_key_value": "some_string"},
         }

res = requests.post(url, json=z_data, headers=header)

我收到字典的值不能是字典的错误。 我尝试使用json.dumps(),但它忽略了其中的内容。

请帮助我解决此错误。谢谢,

【问题讨论】:

  • 请求参数应该是什么?它们必须是字符串...
  • 解决方案实际上只取决于表单期望的 post 参数。那么,表单需要哪些参数呢?
  • @SergeBallesta 是的,它们是字符串,我已经更新了问题
  • @user10987432 它们是用户定义的参数
  • 您不能在 HTTP 请求中传递字典。句号。 HTTP 协议要求任何参数都是字符串。所以问题归结为你想如何格式化字典?

标签: python json python-requests


【解决方案1】:

你必须对参数进行json编码:

header = {
          "content-type": "application/json",
          "a": json.dumps({"b": "b_value"}),
          "some_param": json.dumps({"some_key_value": "some_string"})
         }

如果您收到预构建的 header 字典,则必须对其进行预处理:

header = {
          "content-type": "application/json",
          "a": {"b": "b_value"},
          "some_param": {"some_key_value": "some_string"},
         }

...

header = {k: json.dumps(v) if isinstance(v, dict) else v for k,v in header.items()}
res = requests.post(url, json=z_data, headers=header)

【讨论】:

  • 我之前也使用过 json.dumps() 但无济于事。将字典数据包含在 json.dumps() 中时会被忽略。似乎这是我范围之外的其他问题。不过感谢您的帮助
  • @JohnDoe: 应该是这样...
【解决方案2】:

看起来参数应该是类似json的字符串。 使用 json 模块应该可以,但您可以尝试使用 f-strings:

header = {
          "content-type": "application/json",
          "a": f'{{"b": {b_value} }}',
          "c": f'{{"d": {d_value} }}',
         }

这样你的变量 a 和 c 是字符串,变量 b_value 和 d_value 将被替换为它的内容。

【讨论】:

  • b_value 和 d_value 是字符串,不是变量
  • 在这种情况下,只需在其中放一个字符串:... "a": '{"b": "stringcontent" }'
猜你喜欢
  • 2017-03-21
  • 2012-07-21
  • 2023-03-11
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2011-12-01
相关资源
最近更新 更多