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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
import cherrypy
import json
from lib import uuid
from lib import database
from time import time
import event
def loadAll():
db = database.connect()
db.execute("SELECT event,button_id,time FROM history")
results = []
while True:
try:
button = ()
button.loadFromDb(db.fetchone())
results.append(button.toDict())
except:
break
return results
class Button(object):
def __init__(self):
self.persisted = False
self.id = None
self.status = STATUS_INVENTORY
self.last_pressed = 0
self.history = []
def toDict(self):
return {
'id': self.id,
'status': self.status,
'last_pressed': self.last_pressed
}
def toJSON(self):
return self.toDict()
def loadById(self, id):
db = database.connect()
db.execute("SELECT id,status,last_pressed FROM buttons WHERE id = ?" , (str(id),))
return self.loadFromDb(db.fetchone())
def loadFromDb(self, dbrs):
if dbrs is None:
raise cherrypy.HTTPError(404, 'Button not found')
self.persisted = True
self.id, self.status, self.last_pressed = dbrs
return self
def press(self):
if self.last_pressed:
self.history.insert(0, self.last_pressed)
self.last_pressed = int(time())
return self
def save(self):
db = database.connect()
# validate
if self.id is None:
raise cherrypy.HTTPError(500, "What u doin?")
# upsert: update
elif self.persisted:
db.execute("UPDATE buttons SET status = ?, last_pressed = ? WHERE id = ?",
(self.status, self.last_pressed, self.id,)
)
# upsert: insert
else:
db.execute("INSERT INTO buttons VALUES (?, ?, ?)", (self.id, self.status, self.last_pressed))
db.connection.commit()
return self
def delete(self):
db = database.connect()
if self.id is None:
raise cherrypy.HTTPError(500, "uhh wat")
db.execute("DELETE FROM buttons WHERE id = ?", (self.id,))
db.connection.commit()
return None
|