我一直在挣扎三个星期的时间,现在我在穷途末路。系统管理员是S * TTY开发商:)
我试图构建轻量级的cgi-bin Python脚本收集数据并将其转换成JSON格式。 然后,我用普通的HTML页面,使AJAX查询Python脚本来获取数据,并得出我的图表(周期性,人们喜欢实时的东西)
这些应该尽可能轻,因为他们对树莓工作。
我的一个Python脚本,用来收集数据的
#!的/ usr / bin中/蟒蛇
进口的sqlite3
进口gviz_api
#启用调试
进口cgitb
cgitb.enable()
高清dict_factory(游标,行):
D = {}
为IDX,列在历数(cursor.description中):
D [COL [0] =行[IDX]
回报ð
连接= sqlite3.connect(templog.db)
connection.row_factory = dict_factory
光标= connection.cursor()
cursor.execute(选择温度,从数据从数据状态,其中ID =(SELECT MAX(ID)))
#获取所有或者一个我们会去为所有。
结果= cursor.fetchall()
connection.close()时
架构= {温度(数字,温度),状态(数字,状态)}
数据=结果
#加载到gviz_api.DataTable
data_table = gviz_api.DataTable(架构)
data_table.LoadData(数据)
JSON = data_table.ToJSon(columns_order =(温度,状态),ORDER_BY =TEMP)
#PRINT结果
#PRINT内容类型:应用程序/ JSON ñ N
打印内容类型:应用程序/ JSON
打印
打印JSON
这就像当我打开它在我的浏览器中的魅力和它给了我什么,我需要为谷歌JSAPI corrent格式
{"rows":[{"c":[{"v":21.062},{"v":0}]}],"cols":[{"type":"number","id":"temp","label":"temp"},{"type":"number","id":"status","label":"status"}]}![分析Python特性一](https://p.xsw88.cn/allimgs/daicuo/20230911/2309.png)
下面是我的html,需要从python脚本JSON数据绘制图表
< HTML>
< HEAD>
<! - 加载AJAX API - >
<脚本类型=文/ JavaScript的SRC =https://www.google.com/jsapi>< / SCRIPT>
&LT;脚本类型=文/ JavaScript的SRC =// ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
&LT;脚本类型=文/ JavaScript的&GT;
//将可视化的API和饼图包。
google.load('可视化','1',{'包':['corechart']});
//设置一个回调,当谷歌可视化的API被加载运行。
google.setOnLoadCallback(drawTable);
传播drawTable(){
VAR jsonData = $阿贾克斯({
键入:GET,
网址:http://192.168.1.123:8099/cgi-bin/test.py
数据类型:JSON,
异步:假的
})responseText的;
警报(jsonData);
//创建我们的数据表了从服务器加载JSON数据。
VAR数据=新google.visualization.DataTable(jsonData);
//实例化和绘制我们的图表,传递一些选项。
VAR图=新google.visualization.LineChart(的document.getElementById('chart_div'));
chart.draw(数据,{宽度:400,高度:240});
}
&LT; / SCRIPT&GT;
&LT; /头&GT;
&LT;身体GT;
&LT;! - 事业部,将持有的饼图 - &GT;
&LT; DIV ID =chart_div&GT;&LT; / DIV&GT;
&LT; /身体GT;
&LT; / HTML&GT;
不幸的是我得到了不确定的警报时,HTML是直接使AJAX查询python脚本。
然后我复制JSON输出1:1的纯静态的html文件,并替换AJAX网址为.html,而不是动态的.py,和它的作品
。我的问题是 - 是否有什么我想要做一些限制,或者是有什么毛病我的code
?我的code基于实例 https://developers.google.com/chart/interactive/docs/php_example https://developers.google.com/chart/interactive/docs/dev/gviz_api_lib
解决方案如果我正确地读你的JavaScript,responseText属性仅设置的请求完成后,的。通常情况下,这些东西异步执行,所以你注册一个函数的数据已经被接收后调用。例如,
函数drawTable(){
VAR drawChart =功能(jsonData){
//创建我们的数据表了从服务器加载JSON数据。
VAR数据=新google.visualization.DataTable(jsonData);
//实例化和绘制我们的图表,传递一些选项。
VAR图=新google.visualization.LineChart(的document.getElementById('chart_div'));
chart.draw(数据,{宽度:400,高度:240});
};
$阿贾克斯({
键入:GET,
网址:http://192.168.1.123:8099/cgi-bin/test.py
数据类型:JSON,
异步:假的
})做(drawChart)。
}
更多的例子可以在的jQuery AJAX文档上找到。
I've been struggling three weeks for now and I'm at the dead end. Sysadmins are s*tty developers :)
I'm trying to build lightweight cgi-bin python scripts to collect data and convert it into json format. Then I use plain html page to make ajax query to python scripts to get data and draw my charts (periodically, people love real-time stuff)
These should be as light as possible, because they work on raspberry.
One of my python scripts that collects the data
#!/usr/bin/python
import sqlite3
import gviz_api
# enable debugging
import cgitb
cgitb.enable()
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
connection = sqlite3.connect("templog.db")
connection.row_factory = dict_factory
cursor = connection.cursor()
cursor.execute("select temp, status from data where ID = (select MAX(ID) from data)")
# fetch all or one we'll go for all.
results = cursor.fetchall()
connection.close()
schema = {"temp": ("number", "temp"),"status": ("number", "status")}
data = results
# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(schema)
data_table.LoadData(data)
json = data_table.ToJSon(columns_order=("temp", "status"),order_by="temp")
#print results
#print "Content-type: application/jsonnn"
print "Content-type: application/json"
print
print json
This works like a charm when I open it up on my browser and it gives me what I need in corrent format for Google jsapi
{"rows":[{"c":[{"v":21.062},{"v":0}]}],"cols":[{"type":"number","id":"temp","label":"temp"},{"type":"number","id":"status","label":"status"}]}
Below is my html that needs the json data from python script to draw the chart
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawTable);
function drawTable() {
var jsonData = $.ajax({
type: "GET",
url: "http://192.168.1.123:8099/cgi-bin/test.py",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Unfortunately I got "undefined" alert when html is making ajax query directly to python script.
Then I copied json output 1:1 to plain static html file and replaced ajax URL to .html instead of dynamic .py, and it works.
My question is - are there some limitations for what I'm trying to do or is there something wrong with my code?
My code is based on examples https://developers.google.com/chart/interactive/docs/php_example https://developers.google.com/chart/interactive/docs/dev/gviz_api_lib
解决方案If I'm reading your javascript correctly, the responseText property is only set after the request has completed. Normally, these things execute asynchronously, so you register a function to be called after the data has been received. e.g.
function drawTable() {
var drawChart = function(jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
};
$.ajax({
type: "GET",
url: "http://192.168.1.123:8099/cgi-bin/test.py",
dataType:"json",
async: false
}).done(drawChart);
}
More examples can be found on in the jquery ajax documentation.
相关推荐
最新文章