Commit | Line | Data |
---|---|---|
fbad3a9f | 1 | # GNU MediaGoblin -- federated, autonomous media hosting |
7f4ebeed | 2 | # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS. |
fbad3a9f E |
3 | # |
4 | # This program is free software: you can redistribute it and/or modify | |
5 | # it under the terms of the GNU Affero General Public License as published by | |
6 | # the Free Software Foundation, either version 3 of the License, or | |
7 | # (at your option) any later version. | |
8 | # | |
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU Affero General Public License for more details. | |
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | ||
17 | ||
3c43cfc9 | 18 | from sqlalchemy.ext.declarative import declarative_base |
9f264942 | 19 | from sqlalchemy.orm import scoped_session, sessionmaker, object_session |
7b194a79 | 20 | |
20be9bb7 | 21 | Session = scoped_session(sessionmaker()) |
7b194a79 E |
22 | |
23 | ||
24 | class GMGTableBase(object): | |
25 | query = Session.query_property() | |
26 | ||
03c22862 E |
27 | def get(self, key): |
28 | return getattr(self, key) | |
9f264942 | 29 | |
c60bbe07 E |
30 | def setdefault(self, key, defaultvalue): |
31 | # The key *has* to exist on sql. | |
32 | return getattr(self, key) | |
33 | ||
b39d1f23 | 34 | def save(self): |
9f264942 E |
35 | sess = object_session(self) |
36 | if sess is None: | |
37 | sess = Session() | |
38 | sess.add(self) | |
39 | sess.commit() | |
3c43cfc9 | 40 | |
329e3903 E |
41 | def delete(self, commit=True): |
42 | """Delete the object and commit the change immediately by default""" | |
c60bbe07 E |
43 | sess = object_session(self) |
44 | assert sess is not None, "Not going to delete detached %r" % self | |
45 | sess.delete(self) | |
329e3903 E |
46 | if commit: |
47 | sess.commit() | |
c60bbe07 | 48 | |
3c43cfc9 E |
49 | |
50 | Base = declarative_base(cls=GMGTableBase) | |
de917303 E |
51 | |
52 | ||
53 | class DictReadAttrProxy(object): | |
54 | """ | |
55 | Maps read accesses to obj['key'] to obj.key | |
56 | and hides all the rest of the obj | |
57 | """ | |
58 | def __init__(self, proxied_obj): | |
59 | self.proxied_obj = proxied_obj | |
60 | ||
61 | def __getitem__(self, key): | |
62 | try: | |
63 | return getattr(self.proxied_obj, key) | |
64 | except AttributeError: | |
65 | raise KeyError("%r is not an attribute on %r" | |
66 | % (key, self.proxied_obj)) |