import cherrypy import sqlite3 import json from lib import uuid from lib import database from time import time STATUS_INVENTORY = 0 STATUS_ACTIVE = 1 STATUS_INACTIVE = 2 STATUS_SUSPENDED = 3 STATUS_DEAD = 4 def loadAll(): db = database.connect() db.execute("SELECT id,status,last_pressed FROM buttons") results = [] while True: try: button = 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