第一次在这里发帖,请原谅我没有完全清楚或不遵守指南。我一直试图让这个工作,但到目前为止没有运气,我无法弄清楚为什么。我的时间间隔"表单中的选择器传递得很好但是" setpointval"提交表单时,选择器不会传递。我已经删除了代码以便重新加载,当我调用main()中的sp时,form = cgi.fieldstorage看不到" setpointval"在形式。任何指导都表示赞赏。
以下代码能够根据" timeinterval"从数据库中的数据创建图表。选择器,我希望能够将一个设定点发送到另一个python脚本来控制系统。我在其他脚本中有大部分控件设置,它只是试图让表单保持输入的设定值。
#!/usr/bin/env python
import sqlite3
import sys
import cgi
import cgitb
#---------------------------------------------------------------------------------------------------------------------------------
# global variables
speriod=(15*60)-1
dbname='/var/www/temp_data.db'
setp=0
#sp=get_sp()
#sp = form["setpoint"].value
#---------------------------------------------------------------------------------------------------------------------------------
# print the HTTP header
def printHTTPheader():
print "Content-type: text/html\n\n"
print
#---------------------------------------------------------------------------------------------------------------------------------
# print the HTML head section
# arguments are the page title and the table for the chart
def printHTMLHead(title, table):
print "<head>"
print " <title>"
print title
print " </title>"
print_graph_script(table)
print "</head>"
#---------------------------------------------------------------------------------------------------------------------------------
# get data from the database
# if an interval is passed,
# return a list of records from the database
def get_data(interval):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
if interval == None:
curs.execute("SELECT * FROM temps")
else:
curs.execute("SELECT * FROM temps WHERE timestamp>datetime('now','localtime','-%s hours')" % interval)
rows=curs.fetchall()
conn.close()
return rows
#---------------------------------------------------------------------------------------------------------------------------------
# convert rows from database into a javascript table
def create_table(rows):
chart_table=""
for row in rows[:-1]:
rowstr="['{0}', {1}],\n".format(str(row[0]),str(row[1]))
chart_table+=rowstr
row=rows[-1]
rowstr="['{0}', {1}]\n".format(str(row[0]),str(row[1]))
chart_table+=rowstr
return chart_table
#---------------------------------------------------------------------------------------------------------------------------------
# print the javascript to generate the chart
# pass the table generated from the database info
def print_graph_script(table):
# google chart snippet
chart_code="""
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'Temperature Channel 0'],%s ]);
var options = {
title: 'Temperature'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>"""
print chart_code % (table)
#---------------------------------------------------------------------------------------------------------------------------------
# print the div that contains the graph
def show_graph():
print "<h2>Temperature Chart</h2>"
print '<div id="chart_div" style="width: 900px; height: 500px;"></div>'
#---------------------------------------------------------------------------------------------------------------------------------
# connect to the db and show some stats
# argument option is the number of hours
def show_stats(option,sp):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
if option is None:
option = str(24)
curs.execute("SELECT timestamp,max(temp0) FROM temps WHERE timestamp>datetime('now','localtime','-%s hour') AND timestamp<=datetime('now','localtime')" % option)
rowmax0=curs.fetchone()
rowstrmax0="             {0}                    {1} C".format(str(rowmax0[0]),str(rowmax0[1]))
curs.execute("SELECT timestamp,min(temp0) FROM temps WHERE timestamp>datetime('now','localtime','-%s hour') AND timestamp<=datetime('now','localtime')" % option)
rowmin0=curs.fetchone()
rowstrmin0="             {0}                    {1} C".format(str(rowmin0[0]),str(rowmin0[1]))
curs.execute("SELECT avg(temp0) FROM temps WHERE timestamp>datetime('now','localtime','-%s hour') AND timestamp<=datetime('now','localtime')" % option)
# curs.execute("SELECT avg(temp0) FROM temps WHERE timestamp>datetime('2014-03-18 00:00:00','-%s hour') AND timestamp<=datetime('2014-03-18 20:45:00')" % option)
rowavg0=curs.fetchone()
curs.execute("SELECT MAX(timestamp),temp0 FROM temps")
rownow=curs.fetchone()
rowstrnow="             {0}                    {1} C".format(str(rownow[0]),str(rownow[1]))
print "<hr>"
print "<h2>Current Temperatures     Ch0</h2>"
print rowstrnow
print "<h2>Minimum Temperature   Ch0</h2>"
print rowstrmin0
print "<h2>Maximum Temperature  Ch0</h2>"
print rowstrmax0
print "<h2>Average Temperatures    Ch0</h2>"
print "                                                               %.3f" % rowavg0+" C"
print "<hr>"
print "<h2>In the last hour:</h2>"
print "<table>"
print "<tr><td><strong>Date/Time</strong></td><td><strong>Ch0 Temp</strong>  </td></tr>"
rows=curs.execute("SELECT * FROM temps WHERE timestamp>datetime('now','localtime','-1 hour') AND timestamp<=datetime('now','localtime')")
for row in rows:
rowstr="<tr><td>{0}  </td><td>{1} C  </td></tr>".format(str(row[0]),str(row[1]))
print rowstr
print "</table>"
print "<hr>"
conn.close()
#---------------------------------------------------------------------------------------------------------------------------------
def print_time_selector(option):
print """<form action="/cgi-bin/webgui1.py" method="POST">
Show the temperature logs for
<select name="timeinterval">"""
if option is not None:
if option == "1":
print "<option value=\"1\" selected=\"selected\">the last hour</option>"
else:
print "<option value=\"1\">the last hour</option>"
if option == "6":
print "<option value=\"6\" selected=\"selected\">the last 6 hours</option>"
else:
print "<option value=\"6\">the last 6 hours</option>"
if option == "12":
print "<option value=\"12\" selected=\"selected\">the last 12 hours</option>"
else:
print "<option value=\"12\">the last 12 hours</option>"
if option == "24":
print "<option value=\"24\" selected=\"selected\">the last 24 hours</option>"
else:
print "<option value=\"24\">the last 24 hours</option>"
if option == "48":
print "<option value=\"48\" selected=\"selected\">the last two days</option>"
else:
print "<option value=\"48\">the last two days</option>"
if option == "168":
print "<option value=\"168\" selected=\"selected\">the last week</option>"
else:
print "<option value=\"168\">the last week</option>"
if option == "240":
print "<option value=\"240\" selected=\"selected\">the last 10 days</option>"
else:
print "<option value=\"240\">the last 10 days</option>"
else:
print """<option value="1">the last hour</option>
<option value="6">the last 6 hours</option>
<option value="12">the last 12 hours</option>
<option value="24" selected="selected">the last 24 hours</option>
<option value="48" selected="selected">the last two days</option>
<option value="168" selected="selected">the last week</option>
<option value="240" selected="selected">the last 10 days</option>"""
print """ </select>"""
#---------------------------------------------------------------------------------------------------------------------------------
def print_setpoint_selector(sp):
print """ Setpoint:
<select name="setpointval">"""
if sp is not None:
if sp == "18":
print "<option value=\"18\" selected=\"selected\">18</option>"
else:
print "<option value=\"18\">18</option>"
if sp == "19":
print "<option value=\"19\" selected=\"selected\">19</option>"
else:
print "<option value=\"19\">19</option>"
if sp == "20":
print "<option value=\"20\" selected=\"selected\">20</option>"
else:
print "<option value=\"20\">20</option>"
if sp == "21":
print "<option value=\"21\" selected=\"selected\">21</option>"
else:
print "<option value=\"21\">21</option>"
if sp == "22":
print "<option value=\"22\" selected=\"selected\">22</option>"
else:
print "<option value=\"22\">22</option>"
if sp == "23":
print "<option value=\"23\" selected=\"selected\">23</option>"
else:
print "<option value=\"23\">23</option>"
if sp == "24":
print "<option value=\"24\" selected=\"selected\">24</option>"
else:
print "<option value=\"24\">24</option>"
else:
print """<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>"""
print """ </select>
<input type="submit" value="Display">
</form>"""
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
# check that the option is valid
# and not an SQL injection
def validate_input(option_str):
# check that the option string represents a number
if option_str.isalnum():
# check that the option is within a specific range
if int(option_str) > 0 and int(option_str) <= 240:
return option_str
else:
return None
else:
return None
#------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
# check that the option is valid
# and not an SQL injection
#def validate_input_sp(setpoint_sp):
# # check that the option string represents a number
# if setpoint_sp.isalnum():
# check that the option is within a specific range
# if int(setpoint_sp) > 0 and int(setpoint_sp) <= 24:
# return setpoint_sp
# else:
# return None
# else:
# return None
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
#return the sp passed to the script
def get_sp():
form=cgi.FieldStorage()
if "setpointval" in form:
sp = form["setpointval"].value
return validate_input(sp)
# return sp
else:
# print """ Hello World"""
return None
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
#return the option passed to the script
def get_option():
form=cgi.FieldStorage()
# print form.keys
if "timeinterval" in form:
option = form["timeinterval"].value
return validate_input(option)
else:
return None
#---------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------------
# main function
# This is where the program starts
def main():
cgitb.enable()
# get options that may have been passed to this script
option=get_option()
if option is None:
option = str(24)
#------------------------------------------------
# get options that may have been passed to this script
sp=get_sp()
# print sp
setp=sp
# if sp is None:
# print "NONE"
# sp = str(20)
#------------------------------------------------
# get data from the database
records=get_data(option)
# print the HTTP header
printHTTPheader()
if len(records) != 0:
# convert the data into a table
table=create_table(records)
else:
print "No data found"
return
# start printing the page
print "<html>"
# print the head section including the table
# used by the javascript for the chart
printHTMLHead("Temperature Logger", table)
# print the page body
print "<body>"
print "<h1>Temperature Logger</h1>"
print "<hr>"
print_time_selector(option)
print_setpoint_selector(sp)
show_graph()
show_stats(option,sp)
print "</body>"
print "</html>"
sys.stdout.flush()
if __name__=="__main__":
main()
#---------------------------------------------------------------------------------------------------------------------------------