I am using grafanalib to go format requests to send to Grafana.
I am using the t_oil dataset as reference.
However, after I run my program, I cannot even click on the “Edit button” to go to the information panels.
Link to Grafanalib: GitHub - weaveworks/grafanalib: Python library for building Grafana dashboards
Dataset schema:
public=# \d+ t_oil;
Table "public.t_oil"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
-------------+---------+-----------+----------+---------+----------+--------------+-------------
region | text | | | | extended | |
country | text | | | | extended | |
year | integer | | | | plain | |
production | integer | | | | plain | |
consumption | integer | | | | plain | |
Access method: heap
I think my issue is with how I am formatting the timeseries.
I am putting the SQL expression in ‘expr’.
I am just trying to get the data into the graph, using a SQL command to do so.
I have the Postgres database setup, and I was able to successfully create other graphs, so I know it’s not a datasource issue.
I have two panels because I wanted to make sure that I wasn’t dealing with some kind of default panel.
I should mention I get the following message after I run the program →
200 - b’{“id”:13,“slug”:“python-generated-example-dashboard”,“status”:“success”,“uid”:“”,“url”:“/d//python-generated-example-dashboard”,“version”:1}’
It is a status 200 message, which makes it confusing as I do not know what to do with this, seeing as the panels do not actually appear.
from grafanalib._gen import DashboardEncoder
from grafanalib.core import (
Dashboard, TimeSeries, GaugePanel,
Target, GridPos,
OPS_FORMAT
)
import json
import requests
class GrafanaVisualization:
def __init__(self):
self.expr = ""
def grafanaPostExample(self):
dashboard = Dashboard(
title="Python generated example dashboard",
description="Example dashboard ",
tags=[
'example'
],
timezone="browser",
panels=[
TimeSeries(
title="Python Generated - Oil Example",
dataSource='PostgreSQL_LocalHost_Test',
targets=[
Target(
# datasource='PostgreSQL_LocalHost_Test',
expr='SELECT year AS \"time\", production AS metric FROM t_oil WHERE country=\'USA\'',
legendFormat="{{ handler }}",
refId='A',
),
],
unit=OPS_FORMAT,
gridPos=GridPos(h=8, w=16, x=0, y=0),
),
TimeSeries(
title="Python Generated - Oil Example 2",
dataSource='PostgreSQL_LocalHost_Test',
targets=[
Target(
# datasource='PostgreSQL_LocalHost_Test',
expr='SELECT year AS \"time\", production AS metric FROM t_oil WHERE country=\'USA\'',
legendFormat="{{ handler }}",
refId='A',
),
],
unit=OPS_FORMAT,
gridPos=GridPos(h=8, w=16, x=0, y=0),
),
],
)
return dashboard
# .auto_panel_ids()
def grafanaDashboardCreator(self):
dashboard = self.grafanaPostExample()
dashboardJSON = self.get_dashboard_json(dashboard)
authToken = "<ASSUME WORKING AUTH TOKEN>"
self.sendGrafanaData(dashboardJSON, "localhost:3000", authToken)
def get_dashboard_json(self, dashboard, overwrite=False, message="From python, updated by grafanalib"):
'''
get_dashboard_json generates JSON from grafanalib Dashboard object
:param dashboard - Dashboard() created via grafanalib
'''
# grafanalib generates json which need to pack to "dashboard" root element
return json.dumps(
{
"dashboard": dashboard.to_json_data(),
"overwrite": overwrite,
"message": message
}, sort_keys=True, indent=2, cls=DashboardEncoder)
def sendGrafanaData(self, theData, server, apiKey, verify=True):
headers = {'Authorization': f"Bearer {apiKey}", 'Content-Type': 'application/json', 'Accept': 'application/json'}
print("headers: " + str(headers))
r = requests.post(f"http://{server}/api/dashboards/db", data=theData, headers=headers, verify=verify)
# TODO: add error handling
print(f"{r.status_code} - {r.content}")
def createDataSource(self):
# TODO: Be able to create data sources.
print("Under construction")
return 0
if __name__ == "__main__":
grafana = GrafanaVisualization()
grafana.grafanaDashboardCreator()
Thank you!