无法使用 Python3 模块请求 POST 到 Grafana

Unable to POST to Grafana using Python3 module requests

我正在尝试使用他们的后端 API 在 Grafana 上创建一个仪表板。我首先测试我的 API 令牌是使用 GET 设置的,并成功获得了一个 return 代码 200(如下所示)。然后我尝试使用 POST 创建一个简单的仪表板,但我一直收到 return 代码 400。我很确定它与我尝试发送的有效负载有关,但是我一直想不通。这是我用于 JSON 格式的示例页面的 link。 http://docs.grafana.org/reference/http_api/

import requests


headers = {"Accept": "application/json","Content-Type": "application/json" ,"Authorization": "Bearer xxx"}

r = requests.get("http://www.localhost",headers=headers)
print(r.text)
print(r.status_code)



dashboard = {"id": None,
             "title": "API_dashboard_test",
             "tags": "[CL-5]",
             "timezone": "browser",
             "rows":"[{}]",
             "schemaVersion": 6,
             "version": 0
             }
payload = {"dashboard": "%s" % dashboard}
url = "http://www.localhost/api/dashboards/db"

p = requests.post(url,headers=headers, data=payload)
print(p)
print(p.status_code)
print(p.text)

输出:

200
<Response [400]>
400
[{"classification":"DeserializationError","message":"invalid character 'd' looking for beginning of value"},{"fieldNames":["Dashboard"],"classification":"RequiredError","message":"Required"}]

问题是您的对象不是实际的 json 对象。

您可以将 post 方法与 json=YOUR_PYTHON_OBJECT

一起使用

因此,要修复代码,请将字典更改为仅使用常规 python 字典,使用 json=payload,而不是 data=payload。

因此重构您的代码,您将拥有:

import requests
headers = {"Accept": "application/json",
           "Content-Type": "application/json",
           "Authorization": "Bearer xxx"
           }

r = requests.get("http://www.localhost", headers=headers)
print(r.text)
print(r.status_code)

dashboard = {"id": None,
             "title": "API_dashboard_test",
             "tags": ["CL-5"],
             "timezone": "browser",
             "rows": [{}],
             "schemaVersion": 6,
             "version": 0
             }
payload = {"dashboard": dashboard}
url = "http://www.localhost/api/dashboards/db"

p = requests.post(url, headers=headers, json=payload)
print(p)
print(p.status_code)
print(p.text)

请注意仪表板中的差异,例如,"rows" 从“[{}]”更改为 [{}],因此它是一个 python 对象(包含空字典的列表),而不是字符串。

输出为

200
<Response [200]>
200
{"slug":"api_dashboard_test","status":"success","version":0}