如何在Python 3.7中正确requests.put

Bla*_*ank 3 python python-3.x python-requests datadog

我尝试使用 PUT 方法与 datadog 的 api 进行通信,但失败并出现“400”响应。我已经查看了文档,并且确信我的标头已正确设置并且已指定访问密钥。以下是我正在使用的函数:

def editMonitor(monitor_Data):

api_url = 'https://api.datadoghq.com/api/v1/monitor/' + str(monitor_Data['id'])

response = requests.put(api_url, monitor_Data, headers=headers)

print(response)

if response.status_code == 200:
    return json.loads(response.content.decode('utf-8'))
else:
    return None
Run Code Online (Sandbox Code Playgroud)

下面是标题的组成部分:

headers = {'Content-Type': 'application/json',
           'DD-API-KEY': '**********************',
           'DD-APPLICATION-KEY': '***********************'
           }
Run Code Online (Sandbox Code Playgroud)

到目前为止我看到的其他文章似乎没有回答我的问题。

cre*_*eed 5

如果您查看API documentation,您会发现它要求您将所需的数据发送到请求正文中。

以下是如何使用 requests 模块将数据发送到正文的示例:

data = {
    "message": yourMessageInfo,
    "name": yourNameInfo,
    "object": yourObjectInfo,
    "priority": yourPriorityInfo,
    "query": yourQueryInfo,
    "tags": yourTagsInfo,
    "type": yourTypeInfo
}

response = requests.put(api_url, headers=headers, json=data)
Run Code Online (Sandbox Code Playgroud)

您当然需要填写所有信息。

直接来自文档的另一个示例:

data = {
  "message": "string",
  "name": "string",
  "options": {
    "enable_logs_sample": false,
    "escalation_message": "string",
    "evaluation_delay": "integer",
    "include_tags": false,
    "locked": false,
    "min_failure_duration": "integer",
    "min_location_failed": "integer",
    "new_host_delay": "integer",
    "no_data_timeframe": "integer",
    "notify_audit": false,
    "notify_no_data": false,
    "renotify_interval": "integer",
    "require_full_window": false,
    "restricted_roles": [],
    "silenced": {
      "<any-key>": "integer"
    },
    "synthetics_check_id": "string",
    "threshold_windows": {
      "recovery_window": "string",
      "trigger_window": "string"
    },
    "thresholds": {
      "critical": "number",
      "critical_recovery": "number",
      "ok": "number",
      "unknown": "number",
      "warning": "number",
      "warning_recovery": "number"
    },
    "timeout_h": "integer"
  },
  "priority": "integer",
  "query": "string",
  "tags": [],
  "type": "string"
}

response = requests.put(api_url, headers=headers, json=data)
Run Code Online (Sandbox Code Playgroud)

更多信息见下API documentation图:

所需的标题图像