1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
18 from sqlalchemy
.ext
.declarative
import declarative_base
19 from sqlalchemy
.orm
import scoped_session
, sessionmaker
, object_session
21 Session
= scoped_session(sessionmaker())
24 class GMGTableBase(object):
25 query
= Session
.query_property()
28 return getattr(self
, key
)
30 def setdefault(self
, key
, defaultvalue
):
31 # The key *has* to exist on sql.
32 return getattr(self
, key
)
35 sess
= object_session(self
)
41 def delete(self
, commit
=True):
42 """Delete the object and commit the change immediately by default"""
43 sess
= object_session(self
)
44 assert sess
is not None, "Not going to delete detached %r" % self
50 Base
= declarative_base(cls
=GMGTableBase
)
53 class DictReadAttrProxy(object):
55 Maps read accesses to obj['key'] to obj.key
56 and hides all the rest of the obj
58 def __init__(self
, proxied_obj
):
59 self
.proxied_obj
= proxied_obj
61 def __getitem__(self
, key
):
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
))