编辑:
所以看起来最大的问题是形成你的 JSON 有效负载。根据 geckoboard API 文档,它应该如下所示:
{"api_key" : "some-api-key-goes-here",
"data": {
"y_axis": {
"format": "currency",
"unit": "USD"
},
"series": [
{
"name": "GBP -> USD",
"data": [
1.62529,
1.56991,
1.50420,
1.52265,
1.55356,
1.51930,
1.52148,
1.51173,
1.55170,
1.61966,
1.59255,
1.63762
]
}
]
}
}
在 API 调用期间,您基本上组装了 JSON 有效负载,然后将其发布到带有密钥的地址。widget-key 是 geckoboard 希望您发布到的唯一地址或 URL, api_key 是您帐户的密钥。您希望您的程序工作的流程如下所示:1)收集您的数据 2)将您的数据组装成类似 JSON 的结构(嵌套的字典和列表)3)转储您的 JSON(这意味着将您的 python 特定结构转换为 JSON结构体)。4) 将此 JSON 发布到特定服务器。
这是您更新的代码:
import requests
import json
class Gecko(object):
def __init__(self, widget_key, api_key):
# You put the widget and api_key values here so you can set it once you
# call your object and set it.
self.api_key = api_key
self.widget_key = widget_key
self.payload = {
'api_key' : self.api_key,
'data' : None
}
def push(self):
ret = requests.post(
"https://push.geckoboard.com/v1/send/%s" % self.widget_key,
json.dumps(self.payload),
verify=False
)
if not (ret.status_code == 200 and ret.json().get('success') == True):
raise ValueError(ret.content)
# This function is the batteries included version. It takes all allowable
# values and checks if they have been provided. If so, it'll post.
def line(self, name, data_list, x_axis_labels=None,
x_axis_type=None, y_axis_format=None, y_axis_unit=None):
_data = {"series": [{"name": name,
"data": data_list}]}
# Add x_axis to _data if there is an additional param.
if x_axis_labels is not None or x_axis_type is not None:
_data["x_axis"] = None
if x_axis_labels is not None:
_data["x_axis"]["labels"] = x_axis_labels
if x_axis_type is not None:
_data["x_axis"]["type"] = x_axis_type
# Add y_axis to _data if there are y_axis params.
if y_axis_format is not None or y_axis_unit is not None:
_data['y_axis'] = None
if y_axis_format is not None:
_data["y_axis"]["format"] = y_axis_format
if y_axis_unit is not None:
_data["y_axis"]["unit"] = y_axis_unit
self.payload["data"] = _data
# Usage:
# Step 1: Form your object and assign it to a variable. The class now requires
# widget_key and API key to start off with.
line_widget = Gecko(
widget_key="12345-12315-asfdasdf-asdfasfd",
api_key="1234-1234-1234-1234")
# Step 2: Add data to the payload:
line_widget.line(name="Something Line graph",
data_list=[1,2,3,4,5,6,7],
x_axis_labels=["one", "two", "three", "four", "five", "six", "seven"])
# Step 3: Push the data
line_widget.push()
抱歉,我现在无法测试代码是否正常工作,但我相当有信心它已经完成了 95% 的工作。如果您正在寻找一种更简单的方法,我构建了一个库来处理形成 JSON 并将数据推送到 geckoboard 上的自定义小部件。
您可以查看Geckopush,如果您有任何问题,请告诉我。它目前处于一个比较稳定的版本,我正在积极研究它。