【问题标题】:How to include a list in a Python requests header如何在 Python 请求标头中包含列表
【发布时间】:2020-01-19 01:58:53
【问题描述】:

我对使用 api 很陌生。 我正在使用requests.patch() 访问api,通过发送具有所需状态的开关列表来切换远程设备。我将标题设置为字典,其中一个值是开关列表;这与 api 文档相对应。

data = {"Authorization" : "Bearer key_xxxxxxx",
    "id": "d1234",
    "switches": [{"id": "s1",
        "state": "open"},
        {"id": "s2",
        "state": "closed"}
     ]}
r= requests.patch(url, headers=data)

我得到以下异常:

requests.exceptions.InvalidHeader: Value for header {switches: [{'id': 's1', 'state': 'open'}, {'id': 's2', 'state': 'closed'}]} must be of type str or bytes, not <class 'list'>

api手册很清楚,开关是作为列表发送的,这是它们从requests.get()返回的方式,所以异常似乎与requests语法有关,而不是特定于api。 我显然无法使用 api 密钥等发布实际脚本,所以希望有人能在上面的代码中发现错误。

【问题讨论】:

  • 标题不能有包含列表或其他字典的字典。拆分您的标头和数据,并将它们分别传递给请求。

标签: python python-requests request-headers


【解决方案1】:

将有效负载和标头作为独立于补丁函数的实体传递为:

header = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxxxxx"}
data = [{"id": "d1234",
    "switches": [{"id": "s1",
        "state": "open"},
        {"id": "s2",
        "state": "closed"}
        ]}]
r= requests.patch(url, data=json.dumps(data), headers=header)

请阅读docs

【讨论】:

    【解决方案2】:

    您不能在请求正文中发送数组。它们必须是字符串,接受此请求的 API 需要处理该字符串。您可以将该列表转换为 json 然后发送。并且 API 需要将这个 json 对象转换为数组或任何其他类型。

    import json
    import requests
    
    url = 'your_url'
    your_list = ['some', 'list']
    data = json.dumps(your_list)
    header = {"Authorization": "Token"}
    
    requests.patch(url, data=data, headers=header)
    
    

    【讨论】:

      猜你喜欢
      • 2017-02-24
      • 2019-09-17
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多