-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathndbTools.py
335 lines (271 loc) · 11 KB
/
ndbTools.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
from google.appengine.ext import ndb
import re
import datetime
# function for getting entity from GAE by key
def GetData(key):
return ndb.Key(urlsafe=key).get()
# function for querying GAE
def QueryData(model, queryParams):
newQueryParams = {}
if 'ancestor' in queryParams:
if isinstance(queryParams['ancestor'], basestring):
ancestor = ndb.Key(urlsafe=queryParams['ancestor'])
elif isinstance(queryParams['ancestor'], dict):
ancestor = ndb.Key(urlsafe=queryParams['ancestor']['key'])
else:
raise Exception('invalid key parameter in queryParams: ' + str(queryParams['key']))
newQueryParams['ancestor'] = ancestor
if 'filters' in queryParams:
filterNode = []
for f in queryParams['filters']:
filterNode.append(ndb.FilterNode(f['property'], f['operator'], f['value']))
newQueryParams['filters'] = ndb.AND(*filterNode)
query = model.query(**newQueryParams)
if 'orders' in queryParams:
if queryParams['orders']['direction'] == 'ASC':
query = query.order(getattr(model, queryParams['orders']['property']))
elif queryParams['orders']['direction'] == 'DESC':
query = query.order(-getattr(model, queryParams['orders']['property']))
else:
raise Exception('invalid direction parameter for order: ' + queryParams['orders']['direction'])
return query.fetch()
# function for adding a new GAE entity
def AddData(model, data, parent=None):
entity = _CreateEntity(model, data, parent)
entity.put()
return entity
# private helper function for adding data
def _CreateEntity(model, data, parent=None):
entity = None
if parent:
key = None
if isinstance(parent, ndb.model.KeyProperty):
key = parent
elif isinstance(parent, basestring):
key = ndb.Key(urlsafe=parent)
elif isinstance(parent, dict):
key = ndb.Key(urlsafe=parent['key'])
elif isinstance(parent, list):
key = ndb.Key(pairs=parent)
else:
raise Exception('invalid parent parameter to CreateEntity method')
if key.get():
entity = model(parent=key)
else:
entity = model()
for x in model._properties:
property = model._properties[x]
if x in data:
if property._repeated:
values = _CheckValueIntegrityList(property, data[x])
setattr(entity, x, values)
else:
value = _CheckValueIntegrity(property, data[x])
setattr(entity, x, value)
else:
if property._required:
raise Exception('required attribute ' + x + ' not defined')
return entity
# private helper function for adding data
def _CheckValueIntegrityList(property, data):
values = []
for d in data:
value = _CheckValueIntegrity(property, d)
if value not in values:
values.append(value)
return values
# private helper function for adding data
def _CheckValueIntegrity(property, data):
if isinstance(property, ndb.model.StringProperty):
if isinstance(data, basestring):
return data
else:
raise Exception('property ' + str(property) + ' expects StringProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.TextProperty):
if isinstance(data, basestring):
return data
else:
raise Exception('property ' + str(property) + ' expects TextProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.BooleanProperty):
if isinstance(data, bool):
return data
else:
raise Exception('property ' + str(property) + ' expects BooleanProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.IntegerProperty):
if isinstance(data, int):
return data
else:
raise Exception('property ' + str(property) + ' expects IntegerProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.FloatProperty):
if isinstance(data, float):
return data
elif isinstance(data, int):
return float(data)
else:
raise Exception('property ' + str(property) + ' expects FloatProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.DateProperty):
if isinstance(data, basestring):
return AsDateObject(data)
else:
raise Exception('property ' + str(property) + ' expects StringProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.TimeProperty):
if isinstance(data, basestring):
return AsTimeObject(data)
else:
raise Exception('property ' + str(property) + ' expects StringProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.DateTimeProperty):
if isinstance(data, basestring):
return AsDateTimeObject(data)
else:
raise Exception('property ' + str(property) + ' expects StringProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
elif isinstance(property, ndb.model.StructuredProperty):
return _CreateEntity(property._modelclass, data)
elif isinstance(property, ndb.model.KeyProperty):
(urlsafe, key) = None, None
if isinstance(data, basestring):
urlsafe = data
elif isinstance(data, dict):
urlsafe = data['key']
else:
raise Exception('property ' + str(property) + ' expects KeyProperty: received ' + str(data) + ' ' + str(type(data)) + ' instead')
if urlsafe:
key = ndb.Key(urlsafe=urlsafe)
if key and key.get():
return key
else:
raise Exception('key points to nonexistent object: ' + str(key))
else:
raise Exception('property ' + str(property) + ' not yet implemented')
def DeleteData(key):
if isinstance(key, basestring):
key = ndb.Key(urlsafe=key)
elif isinstance(key, ndb.model.KeyProperty):
pass
else:
raise Exception('invalid key parameter passed to DeleteData')
key.delete()
return
# function for getting an object referenced by 'key'
def GetData(key):
if isinstance(key, basestring):
return ndb.Key(urlsafe=key).get()
elif isinstance(key, dict):
return ndb.Key(urlsafe=key['key'])
else:
raise Exception('unknown key type')
# function for saving a python dict object (obj) into GAE entity (referenced by 'key')
def SaveData(key, obj):
entity = ndb.Key(urlsafe=key).get()
for x in entity.__class__._properties:
property = entity.__class__._properties[x]
if isinstance(property, ndb.model.ComputedProperty):
continue
if property._repeated:
values = []
for d in obj[x]:
value = _CheckValueIntegrity(property, d)
if value not in values:
values.append(value)
setattr(entity, x, values)
else:
value = _CheckValueIntegrity(property, obj[x])
setattr(entity, x, value)
entity.put()
return entity
# function for returning a ndb object as a dictionary
def AsDict(obj, level = 0):
dict = None
entity = None
if isinstance(obj, ndb.Key):
dict = {'id': obj.id(), 'key': obj.urlsafe()}
if level > 2:
return obj.urlsafe()
entity = obj.get()
if entity is None:
return None
elif isinstance(obj, ndb.Model):
dict = {}
entity = obj
else:
raise Exception('invalid parameter obj passed to AsDict')
for p in entity._properties:
attr = getattr(entity, p)
#if p == "shipping":
#print '~~~'
#print attr
#print '~~~'
if isinstance(attr, ndb.Key):
attr = AsDict(attr, level = (level + 1))
elif isinstance(attr, list):
#print 'p: ' + str(p)
#print 'attr: ' + str(attr)
attr = [AsDict(a, level = (level + 1)) for a in attr]
attr = [a for a in attr if not a is None]
elif isinstance(attr, (datetime.datetime, datetime.date, datetime.time)):
attr = str(attr)
dict[p] = attr
return dict
# function for returning a ndb object as a dictionary
def AsDictBACKUP(obj, level = 0):
if isinstance(obj, ndb.Key):
dict = {'id': obj.id(), 'key': obj.urlsafe()}
if obj.get() is None:
return None
if level > 2:
return obj.urlsafe()
for p in obj.get()._properties:
attr = getattr(obj.get(), p)
if p == "shipping":
print '~~~'
print attr
print '~~~'
if isinstance(attr, ndb.Key):
attr = AsDict(attr, level = (level + 1))
elif isinstance(attr, list):
print 'p: ' + str(p)
print 'attr: ' + str(attr)
attr = [AsDict(a, level = (level + 1)) for a in attr]
attr = [a for a in attr if not a is None]
elif isinstance(attr, (datetime.datetime, datetime.date, datetime.time)):
attr = str(attr)
dict[p] = attr
return dict
elif isinstance(obj, ndb.Model):
dict = {}
for p in obj._properties:
print '@@@'
print p
print getattr(obj, p)
print '@@@'
print obj
print type(obj)
print isinstance(obj, ndb.Model)
print '/////'
return '{error: "AsDict()" requires entity key}'
# function for returning a date and time string as a date object
def AsDateTimeObject(dt):
dateTimeMatch = re.match('.*(\d{4}-\d{2}-\d{2}).*(\d{2}:\d{2}).*',dt)
if dateTimeMatch:
dateValue = dateTimeMatch.groups()[0].split('-')
dateValue = [int(dv) for dv in dateValue]
timeValue = dateTimeMatch.groups()[1].split(':')
timeValue = [int(tv) for tv in timeValue]
return datetime.datetime(dateValue[0], dateValue[1], dateValue[2], timeValue[0], timeValue[1])
else:
raise Exception('invalid DateTime parameter: ' + str(dt))
def AsDateObject(d):
dateMatch = re.match('.*(\d{4}-\d{2}-\d{2}).*',d)
if dateMatch:
dateValue = dateMatch.groups()[0].split('-')
dateValue = [int(dv) for dv in dateValue]
return datetime.date(dateValue[0], dateValue[1], dateValue[2])
else:
return Exception('invalid Date parameter: ' + str(d))
def AsTimeObject(t):
timeMatch = re.match('.*(\d{2}:\d{2}).*',t)
if timeMatch:
timeValue = timeMatch.groups()[0].split(':')
timeValue = [int(tv) for tv in timeValue]
return datetime.time(timeValue[0], timeValue[1])
else:
return Exception('invalid Time parameter: ' + str(t))