time = dateparser.parse(rows[0][0]) data = [] for row in rows[1:]: if dateparser.parse(row[0]) - time > timedelta(0, 60): avg = sum(values) / len(values) data.append((time, avg)) time = dateparser.parse(row[0]) values = [float(row[1])] else: values.append(float(row[1])) c.close() datatable = gviz_api.DataTable([("time", "datetime"), ("CO2", "number")], data=data) callback = request.GET.get('responseHandler', 'google.visualization.Query.setResponse') return datatable.ToJSonResponse(response_handler=callback) if os.environ.get('BOTTLE_CHILD'): print "Simulation mode is %s" % ("on" if simulate else "off") create_db() samples = Samples(simulate=simulate) samples.setDaemon(True) samples.start() run(host='0.0.0.0', port=8080, reloader=True)
def create_month_spreadsheet(): today = date.today() start_date = date(today.year, today.month, 1) end_date = today + timedelta(1) print "Generating spreadsheet for current month" sql = "SELECT date,co2 FROM samples WHERE date>=? AND date<? ORDER BY date" params = (start_date.isoformat(), end_date.isoformat()) output = StringIO.StringIO() writer = csv.writer(output) writer.writerow(['Timestamp', 'Avg CO2']) for row in average_rows(sql, params, timedelta(0, 600)): writer.writerow(row) o = open('webroot/month.csv', 'wb') o.write(output.getvalue()) o.close() o = open('webroot/month-%04d%02d.csv' % (today.year, today.month), 'wb') o.write(output.getvalue()) o.close() create_db(DB) synchronize() generate_badge() create_month_spreadsheet()