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

时间:2016-10-10 23:11:10

标签: python-requests python-3.4 grafana

我正在尝试使用他们的后端API在Grafana上创建一个仪表板。我首先测试使用GET设置我的API令牌并成功获得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"}]

1 个答案:

答案 0 :(得分:2)

问题是你的对象不是真正的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)

请注意仪表板中的差异,例如&#34;行&#34;已从&#34; [{}]&#34;更改只是[{}]所以它是一个python对象(带有空字典的列表),而不是一个字符串。

输出

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