/
model.py
245 lines (208 loc) · 8.11 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.sdb.db.manager import get_manager
from boto.sdb.db.property import Property
from boto.sdb.db.key import Key
from boto.sdb.db.query import Query
import boto
class ModelMeta(type):
"Metaclass for all Models"
def __init__(cls, name, bases, dict):
super(ModelMeta, cls).__init__(name, bases, dict)
# Make sure this is a subclass of Model - mainly copied from django ModelBase (thanks!)
cls.__sub_classes__ = []
try:
if filter(lambda b: issubclass(b, Model), bases):
for base in bases:
base.__sub_classes__.append(cls)
cls._manager = get_manager(cls)
# look for all of the Properties and set their names
for key in dict.keys():
if isinstance(dict[key], Property):
property = dict[key]
property.__property_config__(cls, key)
prop_names = []
props = cls.properties()
for prop in props:
if not prop.__class__.__name__.startswith('_'):
prop_names.append(prop.name)
setattr(cls, '_prop_names', prop_names)
except NameError:
# 'Model' isn't defined yet, meaning we're looking at our own
# Model class, defined below.
pass
class Model(object):
__metaclass__ = ModelMeta
__consistent__ = False # Consistent is set off by default
id = None
@classmethod
def get_lineage(cls):
l = [c.__name__ for c in cls.mro()]
l.reverse()
return '.'.join(l)
@classmethod
def kind(cls):
return cls.__name__
@classmethod
def _get_by_id(cls, id, manager=None):
if not manager:
manager = cls._manager
return manager.get_object(cls, id)
@classmethod
def get_by_id(cls, ids=None, parent=None):
if isinstance(ids, list):
objs = [cls._get_by_id(id) for id in ids]
return objs
else:
return cls._get_by_id(ids)
get_by_ids = get_by_id
@classmethod
def get_by_key_name(cls, key_names, parent=None):
raise NotImplementedError, "Key Names are not currently supported"
@classmethod
def find(cls, limit=None, next_token=None, **params):
q = Query(cls, limit=limit, next_token=next_token)
for key, value in params.items():
q.filter('%s =' % key, value)
return q
@classmethod
def all(cls, limit=None, next_token=None):
return cls.find(limit=limit, next_token=next_token)
@classmethod
def get_or_insert(key_name, **kw):
raise NotImplementedError, "get_or_insert not currently supported"
@classmethod
def properties(cls, hidden=True):
properties = []
while cls:
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, Property):
if hidden or not prop.__class__.__name__.startswith('_'):
properties.append(prop)
if len(cls.__bases__) > 0:
cls = cls.__bases__[0]
else:
cls = None
return properties
@classmethod
def find_property(cls, prop_name):
property = None
while cls:
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, Property):
if not prop.__class__.__name__.startswith('_') and prop_name == prop.name:
property = prop
if len(cls.__bases__) > 0:
cls = cls.__bases__[0]
else:
cls = None
return property
@classmethod
def get_xmlmanager(cls):
if not hasattr(cls, '_xmlmanager'):
from boto.sdb.db.manager.xmlmanager import XMLManager
cls._xmlmanager = XMLManager(cls, None, None, None,
None, None, None, None, False)
return cls._xmlmanager
@classmethod
def from_xml(cls, fp):
xmlmanager = cls.get_xmlmanager()
return xmlmanager.unmarshal_object(fp)
def __init__(self, id=None, **kw):
self._loaded = False
# first initialize all properties to their default values
for prop in self.properties(hidden=False):
setattr(self, prop.name, prop.default_value())
if kw.has_key('manager'):
self._manager = kw['manager']
self.id = id
for key in kw:
if key != 'manager':
# We don't want any errors populating up when loading an object,
# so if it fails we just revert to it's default value
try:
setattr(self, key, kw[key])
except Exception, e:
boto.log.exception(e)
def __repr__(self):
return '%s<%s>' % (self.__class__.__name__, self.id)
def __str__(self):
return str(self.id)
def __eq__(self, other):
return other and isinstance(other, Model) and self.id == other.id
def _get_raw_item(self):
return self._manager.get_raw_item(self)
def load(self):
if self.id and not self._loaded:
self._manager.load_object(self)
def reload(self):
if self.id:
self._loaded = False
self._manager.load_object(self)
def put(self):
self._manager.save_object(self)
save = put
def delete(self):
self._manager.delete_object(self)
def key(self):
return Key(obj=self)
def set_manager(self, manager):
self._manager = manager
def to_dict(self):
props = {}
for prop in self.properties(hidden=False):
props[prop.name] = getattr(self, prop.name)
obj = {'properties' : props,
'id' : self.id}
return {self.__class__.__name__ : obj}
def to_xml(self, doc=None):
xmlmanager = self.get_xmlmanager()
doc = xmlmanager.marshal_object(self, doc)
return doc
@classmethod
def find_subclass(cls, name):
"""Find a subclass with a given name"""
if name == cls.__name__:
return cls
for sc in cls.__sub_classes__:
r = sc.find_subclass(name)
if r != None:
return r
class Expando(Model):
def __setattr__(self, name, value):
if name in self._prop_names:
object.__setattr__(self, name, value)
elif name.startswith('_'):
object.__setattr__(self, name, value)
elif name == 'id':
object.__setattr__(self, name, value)
else:
self._manager.set_key_value(self, name, value)
object.__setattr__(self, name, value)
def __getattr__(self, name):
if not name.startswith('_'):
value = self._manager.get_key_value(self, name)
if value:
object.__setattr__(self, name, value)
return value
raise AttributeError