]>
Commit | Line | Data |
---|---|---|
e5424f29 MR |
1 | import abc |
2 | ||
fc01a3eb MR |
3 | class QueryException(Exception): |
4 | pass | |
5 | ||
6 | class OrmSubject(object, metaclass=abc.ABCMeta): | |
e5424f29 MR |
7 | @abc.abstractmethod |
8 | def addObserver(self, ormObserver): | |
9 | pass | |
10 | ||
11 | @abc.abstractmethod | |
12 | def removeObserver(self, ormObserver): | |
13 | pass | |
14 | ||
15 | @abc.abstractmethod | |
16 | def notify(self, subject): | |
17 | pass | |
18 | ||
fc01a3eb | 19 | class Observer(object, metaclass=abc.ABCMeta): |
e5424f29 MR |
20 | @abc.abstractmethod |
21 | def update(self, subject): | |
22 | pass | |
23 | ||
24 | class BaseOrm(OrmSubject): | |
25 | ||
26 | def __init__(self): | |
27 | self.__observers = [] | |
fc01a3eb | 28 | self.__oldValues = {} |
e5424f29 MR |
29 | |
30 | def addObserver(self, ormObserver): | |
31 | print("Added: {0}".format(ormObserver)) | |
32 | self.__observers.append(ormObserver) | |
33 | ||
34 | def removeObserver(self, ormObserver): | |
35 | self.__observers.remove(ormObserver) | |
36 | ||
37 | def notify(self, object): | |
38 | for observer in self.__observers: | |
39 | observer.update(object) | |
40 | ||
fc01a3eb MR |
41 | @classmethod |
42 | def query(cls, **kwargs): | |
43 | objects = [] | |
44 | from app import db | |
45 | if kwargs: | |
46 | if hasattr(cls, '__tablename__'): | |
47 | table = cls.__tablename__ | |
48 | else: | |
49 | table = cls.__name__ | |
50 | o = db.query(table, **kwargs) | |
51 | if table.lower() == 'user': | |
52 | for user in o: | |
53 | objects.append(cls(user[1], user[2], user[3], user[4], user[0])) | |
54 | elif table.lower() == 'portfolio': | |
55 | for portfolio in o: | |
56 | user = db.query('user', id = portfolio[2])[0] | |
57 | objects.append(cls(portfolio[1], user, portfolio[3], portfolio[4], portfolio[0])) | |
58 | else: | |
59 | raise QueryException("{0}: Missing at least one query parameter".format(cls)) | |
60 | return objects | |
61 | ||
62 | def commit(self): | |
63 | self.notify(self) | |
64 | self.__oldValues = {} | |
65 | ||
66 | def rollback(self): | |
67 | for k, v in self.__oldValues.items(): | |
68 | setattr(self, k, v) | |
69 | self.__oldValues = {} | |
70 | ||
e5424f29 MR |
71 | @property |
72 | def id(self): | |
73 | return self.__id | |
74 | ||
75 | @id.setter | |
76 | def id(self, id): | |
e5424f29 | 77 | try: |
fc01a3eb MR |
78 | self.__oldValues['id'] = self.id |
79 | except AttributeError: | |
e5424f29 | 80 | pass |
e5424f29 | 81 | self.__id = id |