使用请求模块将 "curl -X PUT ... - G ..." 转换为 python

Converting a "curl -X PUT ... - G ..." to python using the requests module

我正在尝试编写一些 python 代码来与 New Relic 的 API 交互。我正在使用请求模块。在大多数情况下,我已经成功了,但我遇到了一个 API 调用的问题。他们的文档用示例 curl 命令表示调用:

https://docs.newrelic.com/docs/alerts/rest-api-alerts/new-relic-alerts-rest-api/rest-api-calls-new-relic-alerts (在 "Update notification channels associated with policies" 之下)

curl -X PUT 'https://api.newrelic.com/v2/alerts_policy_channels.json' \
     -H 'X-Api-Key:{admin_api_key}' -i \
     -H 'Content-Type: application/json' \
     -G -d 'policy_id=policy_id&channel_ids=channel_id'

我的主要问题是我不清楚如何使用响应库将 -G 转换为 python。我什至不确定我是否理解该标志的作用,听起来它除了最初的 PUT 之外还发出了额外的获取请求?

我一直在使用这个转换器工具,它适用于我一直使用的大多数 curl 调用,但不适用于这个。

https://curl.trillworks.com/

这是根据上述 curl 命令生成的(不起作用):

import requests

headers = {
    'X-Api-Key': '{admin_api_key}',
    'Content-Type': 'application/json',
}

data = {
  'policy_id': 'policy_id',
  'channel_ids': 'channel_id'
}

response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, data=data)

这基本上是相同的代码,只是包装在我实际使用它的函数中:

def set_alert_policy_notification_channel(admin_api_key, policy_id, notification_channel_id):
    headers = {
        'X-Api-Key': admin_api_key,
        'Content-Type': 'application/json',
    }

    data = {
    'policy_id': policy_id,
    'channel_ids': notification_channel_id
    }

    response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, data=data)
    logging.debug(response)
    return response

当我调用时出现 500 错误,可能是因为请求的格式不正确:

2019-07-11 09:35:31,546 - 调试 - 启动新的 HTTPS 连接 (1):api.newrelic.com:443 2019-07-11 09:35:32,046 - 调试 - https://api.newrelic.com:443 "PUT /v2/alerts_policy_channels.json HTTP/1.1" 500 None 2019-07-11 09:35:32,293 - 调试 -

500 状态代码是内部服务器错误,这意味着服务器由于某些未知原因无法处理请求。我的猜测是您的代码没有任何问题,这是他们端的服务器问题...我确实在他们的网站上注意到了这一点:

https://rpm.newrelic.com/api/explore/applications/update

500 A server error occurred, please contact New Relic support

-G in curl 将您作为 -d/--data(以及类似的)传递的任何内容转换为附加到 URL 的查询参数。

因此,您需要在使用 requests 的 PUT 请求中将 data 作为 params 传递,而不是作为 data。假设您当前的 headersdata 指令:

response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, params=data)

注意 params=data 关键字参数。

set data=json.dumps(data) 而不是 data=data

response = requests.put('https://api.newrelic.com/v2/alerts_policy_channels.json', headers=headers, data=json.dumps(data))