-
Notifications
You must be signed in to change notification settings - Fork 1
/
series.py
70 lines (58 loc) · 2.07 KB
/
series.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from flask import request, make_response
from flask_restful import Resource
from cosmicpi.config import Config
import sqlite3
import io
import csv
SQLITE_LOCATION = Config.get("Storage", "sqlite_location")
class Series(Resource):
def __init__(self):
self._cpuserial = "0000000000000000"
try:
with open('/proc/cpuinfo','r') as f:
for line in f:
if line[0:6]=='Serial':
self._cpuserial = line[10:26]
except:
self._cpuserial = "ERROR100000000"
def get(self):
format = request.args['format']
limit = int(request.args.get('limit', 20))
since = int(request.args.get('from', 0))
to = int(request.args.get('to', 2147483646))
conn = sqlite3.connect(SQLITE_LOCATION, timeout=60.0)
cursor = conn.cursor()
# Get column names
cursor.execute("PRAGMA table_info(Events);")
col_data = cursor.fetchall()
col_names = []
for i in range(0, len(col_data)):
col_names.append(col_data[i][1])
# Get data from database
cursor.execute("SELECT * FROM Events WHERE (UTCUnixTime >= %d AND UTCUnixTime <= %d) ORDER BY UTCUnixTime DESC, SubSeconds DESC LIMIT %d;" % (since, to, limit))
data = cursor.fetchall()
conn.close()
if format == 'json':
return self._get_json(col_names, data)
elif format == 'csv':
return self._get_csv(col_names, data)
def _get_json(self, col_names, data):
items = []
for row in data:
item = {}
item['HardwareSerial'] = self._cpuserial
for i in range(len(col_names)):
item[col_names[i]] = row[i]
items.append(item)
return items
def _get_csv(self, col_names, data):
"""
Write CSV export to memory
"""
output = io.BytesIO()
writer = csv.writer(output)
writer.writerow(col_names)
writer.writerows(data)
response = make_response(output.getvalue())
response.headers['Content-Type'] = 'text/csv'
return response