This repository has been archived by the owner on Aug 27, 2023. It is now read-only.
/
__init__.py
446 lines (376 loc) · 14.7 KB
/
__init__.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
""" Field declarations for models """
import copy
import six
import inspect
import json
from dynamo3 import (DynamoKey, LocalIndex, NUMBER, STRING, BINARY, NUMBER_SET,
STRING_SET, BINARY_SET, is_null)
from decimal import Decimal
from .conditions import Condition
from .indexes import GlobalIndex
from .types import TypeDefinition, ALL_TYPES, set_
NO_ARG = object()
class Field(object):
"""
Declarative way to specify model fields
Parameters
----------
hash_key : bool, optional
This key is a DynamoDB hash key (default False)
range_key : bool, optional
This key is a DynamoDB range key (default False)
index : str, optional
If present, create a local secondary index on this field with this as
the name.
type : object, optional
The field data type. You may use int, unicode, set, etc. or you may
pass in an instance of :class:`~flywheel.fields.types.TypeDefinition`
(default unicode)
coerce : bool, optional
Attempt to coerce the value if it's the incorrect type (default False)
check : callable or list, optional
A function that takes the value and returns True if the value is valid.
May also be a list of such functions. (default None)
nullable : bool, optional
If false, will add a check (above) to ensure the value is not null
(default True).
default : object, optional
The default value for this field that will be set when creating a model
(default None, except for ``set`` data types which default to set())
Attributes
----------
name : str
The name of the attribute on the model
model : class
The :class:`.Model` this field is attached to
composite : bool
True if this is a composite field
Notes
-----
::
Field(index='my-index')
Is shorthand for::
Field().all_index('my-index')
"""
def __init__(self, hash_key=False, range_key=False, index=None,
data_type=NO_ARG, type=six.text_type, coerce=False,
check=None, nullable=True, default=NO_ARG):
if hash_key and range_key:
raise ValueError("hash_key and range_key are mutually exclusive!")
self.name = None
self.model = None
self.composite = False
if data_type is NO_ARG:
data_type = type
if isinstance(data_type, TypeDefinition):
self.data_type = data_type
elif (inspect.isclass(data_type) and
issubclass(data_type, TypeDefinition)):
self.data_type = data_type()
else:
type_factory = ALL_TYPES.get(data_type)
if type_factory is None:
raise TypeError("Unrecognized data_type '%s'" % data_type)
self.data_type = type_factory()
self._coerce = coerce
self.check = []
if check is not None:
if hasattr(check, '__iter__'):
self.check = list(check)
else:
self.check = [check]
if not nullable:
self.check.append(lambda x: not is_null(x))
self.hash_key = hash_key
self.range_key = range_key
self.subfields = []
self.index = False
self.index_name = None
self._ddb_index = None
self._ddb_index_kwargs = None
if default is NO_ARG:
if self.is_set:
self._default = set()
else:
self._default = None
else:
self._default = default
if index:
self.all_index(index)
@property
def default(self):
""" Get a shallow copy of the default value """
return copy.copy(self._default)
def get_ddb_index(self):
""" Construct a dynamo local index object """
range_key = DynamoKey(self.name, data_type=self.ddb_data_type)
return self._ddb_index(self.index_name, range_key,
**self._ddb_index_kwargs)
def _set_ddb_index(self, name, factory, **kwargs):
""" Set the type of index """
if self.hash_key or self.range_key:
raise ValueError("Cannot index the hash or range key!")
if self.index:
raise ValueError("Index is already set!")
self.index_name = name
self._ddb_index = factory
self._ddb_index_kwargs = kwargs
self.index = True
def validate(self, obj):
"""
Run the validation checks for this field on a model object.
Parameters
----------
obj : :class:`~flywheel.models.Model`
Raises
------
err : :class:`ValueError`
Raised if any of the checks fail.
"""
if self.check is None:
return
val = self.resolve(obj)
for check in self.check:
if not check(val):
raise ValueError("Validation check on field %s failed for "
"value %r" % (self.name, val))
def all_index(self, name):
"""
Index this field and project all attributes
Parameters
----------
name : str
The name of the index
"""
self._set_ddb_index(name, LocalIndex.all)
return self
def keys_index(self, name):
"""
Index this field and project all key attributes
Parameters
----------
name : str
The name of the index
"""
self._set_ddb_index(name, LocalIndex.keys)
return self
def include_index(self, name, includes=None):
"""
Index this field and project selected attributes
Parameters
----------
name : str
The name of the index
includes : list, optional
List of non-key attributes to project into this index
"""
includes = includes or []
self._set_ddb_index(name, LocalIndex.include, includes=includes)
return self
def coerce(self, value, force_coerce=None):
""" Coerce the value to the field's data type """
if value is None:
return value
if force_coerce is None:
force_coerce = self._coerce
try:
return self.data_type.coerce(value, force_coerce)
except (TypeError, ValueError) as e:
if e.args:
raise
raise TypeError("Field '%s' must be %s! '%s'" %
(self.name, self.data_type, repr(value)))
@property
def is_mutable(self):
""" Return True if the data type is mutable """
return self.data_type.mutable
@property
def is_set(self):
""" Return True if data type is a set """
return self.ddb_data_type in (STRING_SET, NUMBER_SET, BINARY_SET)
def ddb_dump(self, value):
""" Dump a value to its Dynamo format """
if value is None:
return None
return self.data_type.ddb_dump(value)
def ddb_dump_for_query(self, value):
""" Dump a value to format for use in a Dynamo query """
if value is None:
return None
value = self.coerce(value, force_coerce=True)
return self.ddb_dump(value)
def ddb_load(self, val):
""" Decode a value retrieved from Dynamo """
return self.data_type.ddb_load(val)
@property
def ddb_data_type(self):
""" Get the native DynamoDB data type """
return self.data_type.ddb_data_type
def can_resolve(self, fields):
"""
Check if the provided fields are enough to fully resolve this field
Parameters
----------
fields : list or set
Returns
-------
needed : set
Set of the subfields needed to resolve this field. If empty, then
it cannot be resolved.
"""
needed = set()
# If this field name is found in the fields, that is all that's needed
if self.name in fields:
needed.add(self.name)
elif self.subfields:
# Otherwise, we need ALL of the subfields (only non-empty for
# Composites) to recursively be satisfied
for field in self.subfields:
resolve = self.model.meta_.fields[field].can_resolve(fields)
if not resolve:
return set()
needed.update(resolve)
return needed
def resolve(self, obj=None, scope=None):
""" Resolve a field value from an object or scope dict """
if obj is not None:
return getattr(obj, self.name)
else:
return scope[self.name]
def get_cached_value(self, obj):
""" Get the cached value of a field before any local modifications """
if self.name in obj.__cache__:
return obj.__cache__[self.name]
else:
return self.resolve(obj)
def _make_condition(self, filter, other):
"""
Construct a query condition for a filter on a value
Parameters
----------
filter : str
The name of the filter (e.g. 'eq' or 'lte')
other : object
The value to filter on
"""
other = self.ddb_dump_for_query(other)
if other is None and filter in ('ne', 'eq'):
# Don't bother checking allowed filters because this turns into the
# "exists" filter, which can be done on anything
pass
elif filter not in self.data_type.allowed_filters:
raise TypeError("Cannot use '%s' filter on '%s' field" %
(filter, self.data_type))
return Condition.construct(self.name, filter, other)
def __eq__(self, other):
return self._make_condition('eq', other)
def __ne__(self, other):
return self._make_condition('ne', other)
def __lt__(self, other):
return self._make_condition('lt', other)
def __le__(self, other):
return self._make_condition('lte', other)
def __gt__(self, other):
return self._make_condition('gt', other)
def __ge__(self, other):
return self._make_condition('gte', other)
def _make_contains_condition(self, filter, other):
""" Construct a query condition for 'contains' or 'ncontains' """
if filter not in self.data_type.allowed_filters:
raise TypeError("Cannot use '%s' filter on '%s' field" %
(filter, self.data_type))
return Condition.construct(self.name, filter,
self.data_type.ddb_dump_inner(other))
def contains_(self, other):
""" Create a query condition that this field must contain a value """
return self._make_contains_condition('contains', other)
def ncontains_(self, other):
""" Create a query condition that this field cannot contain a value """
return self._make_contains_condition('ncontains', other)
def in_(self, other):
"""
Create a query condition that this field must be within a set of values
"""
if 'in' not in self.data_type.allowed_filters:
raise TypeError("Cannot use '%s' filter on '%s' field" %
(filter, self.data_type))
else:
other = set([self.ddb_dump_for_query(val) for val in other])
return Condition.construct(self.name, 'in', other)
def beginswith_(self, other):
"""
Create a query condition that this field must begin with a string
"""
if 'beginswith' not in self.data_type.allowed_filters:
raise TypeError("Cannot use 'beginswith' filter on '%s' field" %
self.data_type)
other = self.ddb_dump_for_query(other)
return Condition.construct(self.name, 'beginswith', other)
def between_(self, low, high):
"""
Create a query condition that this field must be between two values
(inclusive)
"""
if 'between' not in self.data_type.allowed_filters:
raise TypeError("Cannot use 'between' filter on %s field" %
self.data_type)
low = self.ddb_dump_for_query(low)
high = self.ddb_dump_for_query(high)
return Condition.construct(self.name, 'between', (low, high))
def betwixt_(self, low, high):
""" Poetic version of :meth:`~.between_` """
return self.between_(low, high)
class Composite(Field):
"""
A field that is composed of multiple other fields
Parameters
----------
*fields : list
List of names of fields that compose this composite field
hash_key : bool, optional
This key is a DynamoDB hash key (default False)
range_key : bool, optional
This key is a DynamoDB range key (default False)
index : str, optional
If present, create a local secondary index on this field with this as
the name.
data_type : str, optional
The dynamo data type. Valid values are (NUMBER, STRING, BINARY,
NUMBER_SET, STRING_SET, BINARY_SET, dict, list, bool, str, unicode,
int, float, set, datetime, date, Decimal) (default unicode)
coerce : bool, optional
Attempt to coerce the value if it's the incorrect type (default False)
check : callable, optional
A function that takes the value and returns True if the value is valid
(default None)
merge : callable, optional
The function that merges the subfields together. By default it simply
joins them with a ':'.
"""
def __init__(self, *args, **kwargs):
self.merge = kwargs.pop('merge', None)
if self.merge is None:
self.merge = lambda *args: ':'.join(args)
unrecognized = (set(kwargs.keys()) -
set(['range_key', 'index', 'hash_key', 'data_type',
'check', 'coerce']))
if unrecognized:
raise TypeError("Unrecognized keyword args: %s" % unrecognized)
if len(args) < 1:
raise TypeError("Composite must depend on at least one field")
super(Composite, self).__init__(**kwargs)
self.composite = True
self.subfields = args
def __contains__(self, key):
return key in self.subfields
def resolve(self, obj=None, scope=None):
""" Resolve a field value from an object or scope dict """
if scope is not None and self.name in scope:
return super(Composite, self).resolve(obj, scope)
args = [self.model.meta_.fields[f].resolve(obj, scope) for f in
self.subfields]
return self.coerce(self.merge(*args))
def get_cached_value(self, obj):
args = [self.model.meta_.fields[f].get_cached_value(obj) for f in
self.subfields]
return self.coerce(self.merge(*args))