forked from gregorynicholas/flask-ndb-api
/
flask_ndb_api.py
246 lines (201 loc) · 6.96 KB
/
flask_ndb_api.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
"""
flask_ndb_api
~~~~~~~~~~~~~~~~~~~
Flask extension for creating an api with App Engine and ndb.
:copyright: (c) 2013 by gregorynicholas.
:license: BSD, see LICENSE for more details.
"""
import logging
from time import mktime
from json import JSONEncoder, loads, dumps
from datetime import date, datetime
from google.appengine.ext import ndb
from google.appengine.ext.ndb import query
__all__ = ['to_epoch', 'from_epoch', 'NDBJSONEncoder', 'entity_to_dict',
'entity_from_dict', 'entity_from_json', 'ndbpprint', 'ndbdumps']
class NDBJSONEncoder(JSONEncoder):
"""
`ndb.Model` JSONencoder class.
Extension of JSONEncoder that can build json from any
`google.appengine.ext.ndb` object.
Provides both a specialized simplejson encoder, ModelEncoder, designed to
simplify encoding directly from NDB Models and query results to json.
"""
def __init__(self, includes=None, excludes=None, **kw):
# these two params are eventually passed down from dumps()
self.__includes = includes
self.__excludes = excludes
JSONEncoder.__init__(self, **kw)
def default(self, obj):
"""
Returns instance of a `dict` from an ndb object.
:param value:
Value to get dictionary for. If not encodable, will call the
superclasses default method.
"""
if isinstance(obj, query.Query):
return list(obj)
elif isinstance(obj, ndb.Cursor):
return obj.urlsafe()
elif isinstance(obj, ndb.BlobKey):
return str(obj)
elif isinstance(obj, ndb.Key):
return obj.urlsafe()
elif hasattr(obj, 'to_dict'):
return getattr(obj, 'to_dict')(
includes=self.__includes,
excludes=self.__excludes)
elif isinstance(obj, datetime):
return to_epoch(obj)
elif isinstance(obj, date):
return to_epoch(datetime(obj.year, obj.month, obj.day))
return JSONEncoder.default(self, obj)
def to_epoch(value):
"""
This is a view method to return the data in milli-seconds.
:param value: Instance of `datetime.datetime`.
:returns: `float` as the number of seconds since unix epoch.
"""
return mktime(value.utctimetuple()) * 1000
def from_epoch(value):
"""
:param value:
Instance of `float` as the number of seconds since unix epoch.
:returns:
Instance of `datetime.datetime`.
"""
return datetime.utcfromtimestamp(value / 1000)
def entity_to_dict(self, includes=None, excludes=None):
"""
Encodes an `ndb.Model` to a `dict`. By default, only `ndb.Property`
attributes are included in the result.
:param include:
List of strings keys of class attributes. Can be the name of the
either a method or property.
:param exclude:
List of string keys to omit from the return value.
:returns: Instance of `dict`.
:raises: `ValueError` if any key in the `include` param doesn't exist.
"""
self._fix_up_properties() # without this we're fucked..
value = ndb.Model.to_dict(self)
# set the `id` of the entity's key by default..
if self.key and (not excludes or 'key' not in excludes):
value['key'] = self.key.urlsafe()
value['key_id'] = self.key.id()
def _to_dict(value):
if callable(value):
return value()
elif isinstance(value, ndb.Model):
return entity_to_dict(value, includes=includes, excludes=excludes)
elif isinstance(value, list):
return [_to_dict(v) for v in value]
else:
return value
if includes:
for inc in includes:
attr = self._properties.get(inc)
if attr is not None:
value[inc] = attr._get_value(self)
continue
logging.warn('entity_to_dict cannot encode `%s`. Property is '
'not defined on `%s.%s`.',
inc, self.__class__.__module__, self.__class__.__name__)
attr = getattr(self, inc, None)
if attr is None:
logging.warn('entity_to_dict cannot encode `%s`. Attribute is '
'not defined on `%s.%s`.',
inc, self.__class__.__module__, self.__class__.__name__)
continue
value[inc] = _to_dict(attr)
if excludes:
# exclude items from the result dict, by popping the keys
# from the dict..
(value.pop(exc) for exc in excludes if exc in value)
return value
def entity_from_dict(cls, value):
"""
:param cls: `ndb.Model` subclass.
:param value: Instance of a `dict`.
"""
entity = cls()
entity._fix_up_properties() # without this we're fucked..
def _decode(_key, _value):
"""
Deserializes `dict`s values to `ndb.Property` values.
"""
prop = entity._properties.get(_key)
if prop is None:
logging.warn('entity_from_dict cannot decode: `%s`. Property is \
not defined on: `%s.%s`.', _key, cls.__module__, cls.__name__)
continue
if isinstance(prop, (ndb.DateTimeProperty, ndb.DateProperty,
ndb.TimeProperty)):
if prop._repeated:
val = [from_epoch(v) for v in _value if v is not None]
elif val:
val = from_epoch(val)
if isinstance(prop, ndb.BlobKeyProperty):
if prop._repeated:
val = [ndb.BlobKey(str(v)) for v in _value if v is not None]
elif val:
val = ndb.BlobKey(str(val))
if isinstance(prop, ndb.KeyProperty):
if prop._repeated:
val = [ndb.Key(urlsafe=v) for v in _value if v is not None]
elif val:
val = ndb.Key(urlsafe=val)
if isinstance(prop, ndb.BlobProperty):
# not supported..
pass
return val
values = {k: _decode(k, v) for k, v in value.iteritems()}
entity.populate(**values)
return entity
def entity_from_json(cls, value):
"""
Deserializes a json str to an instance of an `ndb.Model` subclass.
:param cls: `ndb.Model` subclass.
:param value: Instance of json data.
"""
value = loads(value, strict=False)
if isinstance(value, list):
result = [entity_from_dict(cls, v) for v in value]
else:
result = entity_from_dict(cls, value)
return result
def ndbdumps(value, includes=None, excludes=None):
"""
:param value:
:param include:
List of string keys of class attributes. Can be the name of the
either a callable method or property.
:param exclude:
List of string keys to omit from the return value.
:returns: JSON string.
"""
return dumps(value,
cls=NDBJSONEncoder, includes=includes, excludes=excludes)
def ndbpprint(model, level=1):
"""
Pretty prints an `ndb.Model`.
"""
body = ['<', type(model).__name__, ':']
values = model.to_dict()
for key, field in model._properties.iteritems():
value = values.get(key)
if value is not None:
body.append('\n%s%s: %s' % (
' '.join([' ' for idx in range(level)]), key, repr(value)))
body.append('>')
return ''.join(body)
def key_or_none(value):
"""
Attempts to parse a value into an instance of an `ndb.Key`.
:returns: None if value cannot be converted to an `ndb.Key`.
"""
if not value:
return None
if isinstance(value, str) and len(value) < 1:
return None
return ndb.Key(urlsafe=value)