2016-10-10 44 views
1

我試圖使用他們的後端API在Grafana上創建儀表板。我首先測試了我的API令牌是通過使用GET設置的,併成功獲得了200的返回碼(如下所示)。然後我嘗試使用POST創建一個簡單的儀表板,但我一直得到400的返回碼。我很確定它與我要發送的有效載荷有關,但我一直無法弄清楚。這裏是我用於他們的JSON格式的示例頁面的鏈接。 http://docs.grafana.org/reference/http_api/無法使用Python3模塊請求發佈到Grafana

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) 

OUTPUT:

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

'有效載荷= { 「儀表板」:儀表盤}' –

+0

http://stackoverflow.com/questions/39954475/post-request-works-in-postman-but-not -python/39954514#39954514, –

+0

@PadraicCunningham這是我遇到的一個問題。我還需要更改其他參數的語法,這些參數與將Python對象轉換爲json字符串時引用不正確,如下所示,謝謝。 –

回答

2

的問題是,你的對象不是一個實際的JSON對象。

您可以使用方法後使用JSON = YOUR_PYTHON_OBJECT

所以解決您的代碼,改變你的字典使用只是一個普通的Python字典,使用JSON =有效載荷,而不是數據=有效載荷。

所以重構你的代碼,你將有:

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) 

注意,在儀表板例如差異,「行」是從「[{}]」剛剛[{}],使其是一個python對象(帶有空字典的列表),而不是一個字符串。

輸出是

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