【问题标题】:Unable to POST to Grafana using Python3 module requests无法使用 Python3 模块请求 POST 到 Grafana
【发布时间】:2016-10-10 23:11:10
【问题描述】:

我正在尝试使用 Grafana 的后端 API 在 Grafana 上创建仪表板。我首先测试我的 API 令牌是使用 GET 设置的,并成功获得返回码 200(如下所示)。然后我尝试使用 POST 创建一个简单的仪表板,但我一直收到 400 的返回码。我很确定这与我尝试发送的有效负载有关,但我一直无法弄清楚.这是我用于他们的 JSON 格式的示例页面的链接。 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"}]

【问题讨论】:

  • payload = {"dashboard": dashboard}
  • @PadraicCunningham 这是我遇到的一个问题。我还需要更改被错误引用的其余参数的语法,并将 python 对象转换为 json 字符串,如下所示,谢谢。

标签: python-requests python-3.4 grafana


【解决方案1】:

问题是您的对象不是真正的 json 对象。

您可以使用带有 json=YOUR_PYTHON_OBJECT 的 post 方法

因此,要修复您的代码,请将您的字典更改为仅使用常规 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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多