Python script to post data to geckoboard

1.1k Views Asked by At

I am looking for help in creating a python script that will push data, specifically to geckoboard in the form of a line graph. Currently the code I have is shown below that has been pulled together from other sources, it would be great if someone could collaborate and help me finish this, I don't know how to insert the values I want on the line graph, if it could be finished with some example values that would be great. Thanks

import requests
import json

class Gecko(object):
def __init__(self, api_key):
    self.api_key = api_key

def push(self, widget_key, data):
    ret = requests.post("https://push.geckoboard.com/v1/send/%s" % widget_key, json.dumps({'api_key' : self.api_key, 'data' : data}), verify=False)
    if not (ret.status_code == 200 and ret.json().get('success') == True):
        raise ValueError(ret.content)

def line(self, widget_key, values, **kwargs):
    data = {'item' : [], 'settings' :kwargs}
    for item in values:
        data['item'].append(item)
    return self.push(widget_key, data)

run=Gecko(****************)
print run.push(150634-85f8db34-af52-4fa3-9963-3200a9a6fe74,some_data?)
print run.line(150634-85f8db34-af52-4fa3-9963-3200a9a6fe74,100,'text')
2

There are 2 best solutions below

0
On

SOLUTION:

File called test.py

import requests
import json

class Gecko(object):
def __init__(self, api_key):
    self.api_key = api_key

def push(self,data):
    ret = requests.post("paste URL here", data=json.dumps(data), verify=False)
    if not (ret.status_code == 200 and ret.json().get('success') == True):
        raise ValueError(ret.content)

File called test1.py

 from test import Gecko
 gecko=Gecko("*************")
 gecko.push({
"api_key": "**************", 
"data": {   
"x_axis": {
        "labels": ["Week 1", "Week 2", "Week 3", "Week 4"]
    },
    "series": [
        {
            "data": [
                10000, 13500, 21000, 1900
            ]
        }
    ]
}
})
0
On

Edit: So the biggest issue it seems is forming your JSON payload. According to the geckoboard API docs, it should look like this:

{"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
          ]
        }
      ]
    }
 }

During an API call, you basically assemble a JSON payload, then post it to an address with a key. The widget-key is the unique address or URL that geckoboard wants you to post to, the api_key is your account's key. The flow you want your program to work in goes like this: 1) Gather your data 2) Assemble your data into a JSON like structure (dictionaries and lists nested) 3) Dump your JSON (This means convert your python specific structure into a JSON structure). 4) Post this JSON to the specific server.

Here is your updated code:

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()

Sorry, I can't test to see if the code works right now, but I'm fairly confident it's 95% of the way there. If you're looking for a simpler way, I built a library that handles forming the JSON and pushing the data to custom widgets on geckoboard.

You can check out Geckopush and let me know if you have any questions. It's currently at a somewhat stable version now and I'm actively working on it.