import abc class QueryException(Exception): pass class OrmSubject(object, metaclass=abc.ABCMeta): @abc.abstractmethod def addObserver(self, ormObserver): pass @abc.abstractmethod def removeObserver(self, ormObserver): pass @abc.abstractmethod def notify(self, subject): pass class Observer(object, metaclass=abc.ABCMeta): @abc.abstractmethod def update(self, subject): pass class BaseOrm(OrmSubject): def __init__(self): self.__observers = [] self.__oldValues = {} def addObserver(self, ormObserver): print("Added: {0}".format(ormObserver)) self.__observers.append(ormObserver) def removeObserver(self, ormObserver): self.__observers.remove(ormObserver) def notify(self, object): for observer in self.__observers: observer.update(object) @classmethod def query(cls, **kwargs): objects = [] from app import db if kwargs: if hasattr(cls, '__tablename__'): table = cls.__tablename__ else: table = cls.__name__ o = db.query(table, **kwargs) if table.lower() == 'user': for user in o: objects.append(cls(user[1], user[2], user[3], user[4], user[0])) elif table.lower() == 'portfolio': for portfolio in o: user = db.query('user', id = portfolio[2])[0] objects.append(cls(portfolio[1], user, portfolio[3], portfolio[4], portfolio[0])) else: raise QueryException("{0}: Missing at least one query parameter".format(cls)) return objects def commit(self): self.notify(self) self.__oldValues = {} def rollback(self): for k, v in self.__oldValues.items(): setattr(self, k, v) self.__oldValues = {} @property def id(self): return self.__id @id.setter def id(self, id): try: self.__oldValues['id'] = self.id except AttributeError: pass self.__id = id