【问题标题】:Python requests PUT request with json parameter fails and data parameter succeedspython请求带json参数的PUT请求失败,data参数成功
【发布时间】:2023-02-03 11:16:17
【问题描述】:

问题

我查看了一些关于 jsondata 参数以及它们之间的区别的文档。在我看来,我想我理解其中的区别,最好的解释是 here

但是,我有一个特定的请求,使用 jsonPUT 上失败,但使用 data 失败,我不确定为什么。有人可以澄清为什么会这样吗?难道payload里面有list?

语境

我安装了requests==2.28.0。下面是将 PUT 请求提交给事件管理软件 PagerDuty 的 API 的代码,一个使用 data(成功),另一个使用 json(失败)。否则它们是相同的。

奇怪的是their examples使用了json参数。

payload = f'{{"source_incidents": [{{"id": "{child_incident_id}", "type": "incident_reference"}}]}}'

headers = {
    'Content-Type': "application/json",
    'Accept': "application/vnd.pagerduty+json;version=2",
    'From': email,
    'Authorization': f"Token token={read_write_api_token}"
    }

response = requests.put(f'https://api.pagerduty.com/incidents/{parent_incident_id}/merge', data=payload, headers=headers)

print("response: ", response)

结果:response: <Response [200]>

payload = f'{{"source_incidents": [{{"id": "{child_incident_id}", "type": "incident_reference"}}]}}'

headers = {
    'Content-Type': "application/json",
    'Accept': "application/vnd.pagerduty+json;version=2",
    'From': email,
    'Authorization': f"Token token={read_write_api_token}"
    }

response = requests.put(f'https://api.pagerduty.com/incidents/{parent_incident_id}/merge', json=payload, headers=headers)

print("response: ", response)

结果:response: <Response [400]>

【问题讨论】:

    标签: python json http python-requests


    【解决方案1】:

    您的有效载荷是一个字符串,而 json 参数采用字典。这就是 json 参数的全部要点(您不必自己对其进行编码):

    如果你需要那个 header set 而你不想自己编码 dict ,你也可以直接使用 json 参数传递它(在版本 2.4.2 中添加)它会自动编码:

    如果你想使用 json 参数,你应该传递一个字典:

    payload = {
        "source_incidents": [
            {
                "id": child_incident_id,
                "type": "incident_reference"
            }
        ]
    }
    

    无论如何,这更具可读性。

    【讨论】:

    • 啊,有道理。天哪,你错过了其中最明显的东西。
    【解决方案2】:

    或者你可以使用 json.loads 来解析你的字符串:

    import json
    payload = f'{{"source_incidents": [{{"id": "{child_incident_id}", "type": "incident_reference"}}]}}'
    headers = {
        'Content-Type': "application/json",
        'Accept': "application/vnd.pagerduty+json;version=2",
        'From': email,
        'Authorization': f"Token token={read_write_api_token}"
        }
    
    response = requests.put(f'https://api.pagerduty.com/incidents/{parent_incident_id}/merge', data=json.loads(payload), headers=headers)
    
    print("response: ", response)
    

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 2017-12-05
      • 2011-11-03
      相关资源
      最近更新 更多