1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
"""This module provides facilities for serializable, validatable, and type-enforcing |
3
|
|
|
domain objects. |
4
|
|
|
|
5
|
|
|
This module has many of the same motivations as the python Marshmallow package. |
6
|
|
|
<http://marshmallow.readthedocs.org/en/latest/why.html> |
7
|
|
|
|
8
|
|
|
Also need to be explicit in explaining what Marshmallow doesn't do, and why this module is needed. |
9
|
|
|
- Provides type safety like an ORM. And like an ORM, all classes subclass Entity. |
10
|
|
|
- Provides BUILT IN serialization and deserialization. Marhmallow requires a lot of code |
11
|
|
|
duplication. |
12
|
|
|
|
13
|
|
|
This module gives us: |
14
|
|
|
- type safety |
15
|
|
|
- custom field validation |
16
|
|
|
- serialization and deserialization |
17
|
|
|
- rock solid foundational domain objects |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
Comparison to schematics: |
21
|
|
|
- no get_mock_object method (yet) |
22
|
|
|
- no context-dependent serialization or MultilingualStringType |
23
|
|
|
- name = StringType(serialized_name='person_name') |
24
|
|
|
- name = StringType(serialize_when_none=False) |
25
|
|
|
- more flexible validation error messages |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
TODO: |
29
|
|
|
- alternate field names |
30
|
|
|
- add dump_if_null field option |
31
|
|
|
- consider adding immutability, maybe ImmutableEntity |
32
|
|
|
- consider making individual fields immutable |
33
|
|
|
|
34
|
|
|
|
35
|
|
|
Optional Field Properties: |
36
|
|
|
- validation = None |
37
|
|
|
- default = None |
38
|
|
|
- required = True |
39
|
|
|
- in_dump = True |
40
|
|
|
- nullable = False |
41
|
|
|
|
42
|
|
|
Behaviors: |
43
|
|
|
- Nullable is a "hard" setting, in that the value is either always or never allowed to be None. |
44
|
|
|
- What happens then if required=False and nullable=False? |
45
|
|
|
- The object can be init'd without a value (though not with a None value). |
46
|
|
|
getattr throws AttributeError |
47
|
|
|
- Any assignment must be not None. |
48
|
|
|
|
49
|
|
|
|
50
|
|
|
- Setting a value to None doesn't "unset" a value. (That's what del is for.) And you can't |
51
|
|
|
del a value if required=True, nullable=False, default=None. That should raise |
52
|
|
|
OperationNotAllowedError. |
53
|
|
|
|
54
|
|
|
- If a field is not required, del does *not* "unmask" the default value. Instead, del |
55
|
|
|
removes the value from the object entirely. To get back the default value, need to recreate |
56
|
|
|
the object. Entity.from_objects(old_object) |
57
|
|
|
|
58
|
|
|
|
59
|
|
|
- Disabling in_dump is a "hard" setting, in that with it disabled the field will never get |
60
|
|
|
dumped. With it enabled, the field may or may not be dumped depending on its value and other |
61
|
|
|
settings. |
62
|
|
|
|
63
|
|
|
- Required is a "hard" setting, in that if True, a valid value or default must be provided. None |
64
|
|
|
is only a valid value or default if nullable is True. |
65
|
|
|
|
66
|
|
|
- In general, nullable means that None is a valid value. |
67
|
|
|
- getattr returns None instead of raising Attribute error |
68
|
|
|
- If in_dump, field is given with null value. |
69
|
|
|
- If default is not None, assigning None clears a previous assignment. Future getattrs return |
70
|
|
|
the default value. |
71
|
|
|
- What does nullable mean with default=None and required=True? Does instantiation raise |
72
|
|
|
an error if assignment not made on init? Can IntField(nullable=True) be init'd? |
73
|
|
|
|
74
|
|
|
- If required=False and nullable=False, field will only be in dump if field!=None. |
75
|
|
|
Also, getattr raises AttributeError. |
76
|
|
|
- If required=False and nullable=True, field will be in dump if field==None. |
77
|
|
|
|
78
|
|
|
- If in_dump is True, does default value get dumped: |
79
|
|
|
- if no assignment, default exists |
80
|
|
|
- if nullable, and assigned None |
81
|
|
|
- How does optional validation work with nullable and assigning None? |
82
|
|
|
- When does gettattr throw AttributeError, and when does it return None? |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
|
86
|
|
|
|
87
|
|
|
|
88
|
|
|
Examples: |
89
|
|
|
# ## Chapter 1: Entity and Field Basics ## |
90
|
|
|
>>> class Color(Enum): |
91
|
|
|
... blue = 0 |
92
|
|
|
... black = 1 |
93
|
|
|
... red = 2 |
94
|
|
|
>>> class Car(Entity): |
95
|
|
|
... weight = NumberField(required=False) |
96
|
|
|
... wheels = IntField(default=4, validation=lambda x: 3 <= x <= 4) |
97
|
|
|
... color = EnumField(Color) |
98
|
|
|
|
99
|
|
|
>>> # create a new car object |
100
|
|
|
>>> car = Car(color=Color.blue, weight=4242.42) |
101
|
|
|
>>> car |
102
|
|
|
Car(weight=4242.42, color=0) |
103
|
|
|
|
104
|
|
|
>>> # it has 4 wheels, all by default |
105
|
|
|
>>> car.wheels |
106
|
|
|
4 |
107
|
|
|
|
108
|
|
|
>>> # but a car can't have 5 wheels! |
109
|
|
|
>>> car.wheels = 5 |
110
|
|
|
Traceback (most recent call last): |
111
|
|
|
ValidationError: Invalid value 5 for wheels |
112
|
|
|
|
113
|
|
|
>>> # we can call .dump() on car, and just get back a standard python dict |
114
|
|
|
>>> # actually, it's ordereddict to preserve attribute declaration order |
115
|
|
|
>>> type(car.dump()) |
116
|
|
|
<class 'collections.OrderedDict'> |
117
|
|
|
>>> car.dump() |
118
|
|
|
OrderedDict([('weight', 4242.42), ('wheels', 4), ('color', 0)]) |
119
|
|
|
|
120
|
|
|
>>> # and json too |
121
|
|
|
>>> car.json() |
122
|
|
|
'{"weight": 4242.42, "wheels": 4, "color": 0}' |
123
|
|
|
|
124
|
|
|
>>> # green cars aren't allowed |
125
|
|
|
>>> car.color = "green" |
126
|
|
|
Traceback (most recent call last): |
127
|
|
|
ValidationError: 'green' is not a valid Color |
128
|
|
|
|
129
|
|
|
>>> # but black cars are! |
130
|
|
|
>>> car.color = "black" |
131
|
|
|
>>> car.color |
132
|
|
|
<Color.black: 1> |
133
|
|
|
|
134
|
|
|
>>> # car.color really is an enum, promise |
135
|
|
|
>>> type(car.color) |
136
|
|
|
<enum 'Color'> |
137
|
|
|
|
138
|
|
|
>>> # let's do a round-trip marshalling of this thing |
139
|
|
|
>>> same_car = Car.from_json(car.json()) # or equally Car.from_json(json.dumps(car.dump())) |
140
|
|
|
>>> same_car == car |
141
|
|
|
True |
142
|
|
|
|
143
|
|
|
>>> # actually, they're two different instances |
144
|
|
|
>>> same_car is not car |
145
|
|
|
True |
146
|
|
|
|
147
|
|
|
>>> # this works too |
148
|
|
|
>>> cloned_car = Car(**car.dump()) |
149
|
|
|
>>> cloned_car == car |
150
|
|
|
True |
151
|
|
|
|
152
|
|
|
# ## Chapter 2: Entity and Field Composition ## |
153
|
|
|
>>> # now let's get fancy |
154
|
|
|
>>> class Fleet(Entity): |
155
|
|
|
... boss_car = ComposableField(Car) |
156
|
|
|
... cars = ListField(Car) |
157
|
|
|
|
158
|
|
|
>>> # here's our fleet of company cars |
159
|
|
|
>>> company_fleet = Fleet(boss_car=Car(color='red'), cars=[car, same_car, cloned_car]) |
160
|
|
|
>>> company_fleet.pretty_json() #doctest: +SKIP |
161
|
|
|
{ |
162
|
|
|
"boss_car": { |
163
|
|
|
"color": 2, |
164
|
|
|
"wheels": 4 |
165
|
|
|
}, |
166
|
|
|
"cars": [ |
167
|
|
|
{ |
168
|
|
|
"color": 1, |
169
|
|
|
"weight": 4242.42, |
170
|
|
|
"wheels": 4 |
171
|
|
|
}, |
172
|
|
|
{ |
173
|
|
|
"color": 1, |
174
|
|
|
"weight": 4242.42, |
175
|
|
|
"wheels": 4 |
176
|
|
|
}, |
177
|
|
|
{ |
178
|
|
|
"color": 1, |
179
|
|
|
"weight": 4242.42, |
180
|
|
|
"wheels": 4 |
181
|
|
|
} |
182
|
|
|
] |
183
|
|
|
} |
184
|
|
|
|
185
|
|
|
>>> # the boss' car is red of course (and it's still an Enum) |
186
|
|
|
>>> company_fleet.boss_car.color.name |
187
|
|
|
'red' |
188
|
|
|
|
189
|
|
|
>>> # and there are three cars left for the employees |
190
|
|
|
>>> len(company_fleet.cars) |
191
|
|
|
3 |
192
|
|
|
|
193
|
|
|
>>> # because we can |
194
|
|
|
>>> sum(c.weight for c in company_fleet.cars) |
195
|
|
|
12727.26 |
196
|
|
|
|
197
|
|
|
# ## Chapter 3: The del and null weeds ## |
198
|
|
|
>>> old_date = lambda: dateparse('1982-02-17') |
199
|
|
|
>>> class CarBattery(Entity): |
200
|
|
|
... # NOTE: default value can be a callable! |
201
|
|
|
... first_charge = DateField(required=False) # default=None, nullable=False |
202
|
|
|
... latest_charge = DateField(default=old_date, nullable=True) # required=True |
203
|
|
|
... expiration = DateField(default=old_date, required=False, nullable=False) |
204
|
|
|
|
205
|
|
|
# starting point |
206
|
|
|
>>> battery = CarBattery() |
207
|
|
|
>>> battery |
208
|
|
|
CarBattery() |
209
|
|
|
>>> battery.json() |
210
|
|
|
'{"latest_charge": "1982-02-17T00:00:00", "expiration": "1982-02-17T00:00:00"}' |
211
|
|
|
|
212
|
|
|
# first_charge is not assigned a default value. Once one is assigned, it can be deleted, |
213
|
|
|
# but it can't be made null. |
214
|
|
|
>>> battery.first_charge = dateparse('2016-03-23') |
215
|
|
|
>>> battery |
216
|
|
|
CarBattery(first_charge=datetime.datetime(2016, 3, 23, 0, 0)) |
217
|
|
|
>>> battery.first_charge = None |
218
|
|
|
Traceback (most recent call last): |
219
|
|
|
ValidationError: Value for first_charge not given or invalid. |
220
|
|
|
>>> del battery.first_charge |
221
|
|
|
>>> battery |
222
|
|
|
CarBattery() |
223
|
|
|
|
224
|
|
|
# latest_charge can be null, but it can't be deleted. The default value is a callable. |
225
|
|
|
>>> del battery.latest_charge |
226
|
|
|
Traceback (most recent call last): |
227
|
|
|
AttributeError: The latest_charge field is required and cannot be deleted. |
228
|
|
|
>>> battery.latest_charge = None |
229
|
|
|
>>> battery.json() |
230
|
|
|
'{"latest_charge": null, "expiration": "1982-02-17T00:00:00"}' |
231
|
|
|
|
232
|
|
|
# expiration is assigned by default, can't be made null, but can be deleted. |
233
|
|
|
>>> battery.expiration |
234
|
|
|
datetime.datetime(1982, 2, 17, 0, 0) |
235
|
|
|
>>> battery.expiration = None |
236
|
|
|
Traceback (most recent call last): |
237
|
|
|
ValidationError: Value for expiration not given or invalid. |
238
|
|
|
>>> del battery.expiration |
239
|
|
|
>>> battery.json() |
240
|
|
|
'{"latest_charge": null}' |
241
|
|
|
|
242
|
|
|
# ## onward ## |
243
|
|
|
>>> class ImmutableCar(ImmutableEntity): |
244
|
|
|
... wheels = IntField(default=4, validation=lambda x: 3 <= x <= 4) |
245
|
|
|
... color = EnumField(Color) |
246
|
|
|
>>> icar = ImmutableCar(wheels=3, color='blue') |
247
|
|
|
>>> icar |
248
|
|
|
ImmutableCar(wheels=3, color=0) |
249
|
|
|
|
250
|
|
|
>>> icar.wheels = 4 |
251
|
|
|
Traceback (most recent call last): |
252
|
|
|
AttributeError: Assignment not allowed. ImmutableCar is immutable. |
253
|
|
|
|
254
|
|
|
|
255
|
|
|
""" |
256
|
|
|
from __future__ import absolute_import, division, print_function |
257
|
|
|
|
258
|
|
|
from collections import Iterable, OrderedDict as odict |
259
|
|
|
from datetime import datetime |
260
|
|
|
from enum import Enum |
261
|
|
|
from functools import reduce |
262
|
|
|
from json import loads as json_loads, dumps as json_dumps |
263
|
|
|
from logging import getLogger |
264
|
|
|
|
265
|
|
|
from ._vendor.dateutil.parser import parse as dateparse |
266
|
|
|
from ._vendor.five import with_metaclass, items, values |
267
|
|
|
from ._vendor.six import integer_types, string_types |
268
|
|
|
from .collection import AttrDict |
269
|
|
|
from .exceptions import ValidationError, Raise |
270
|
|
|
from .ish import find_or_none |
271
|
|
|
from .type_coercion import maybecall |
272
|
|
|
|
273
|
|
|
log = getLogger(__name__) |
274
|
|
|
|
275
|
|
|
__all__ = [ |
276
|
|
|
"Field", "BooleanField", "BoolField", "IntegerField", "IntField", |
277
|
|
|
"NumberField", "StringField", "DateField", |
278
|
|
|
"EnumField", "ListField", "MapField", "ComposableField", |
279
|
|
|
"Entity", "ImmutableEntity", |
280
|
|
|
] |
281
|
|
|
|
282
|
|
|
KEY_OVERRIDES_MAP = "__key_overrides__" |
283
|
|
|
|
284
|
|
|
|
285
|
|
|
class Field(object): |
286
|
|
|
""" |
287
|
|
|
Fields are doing something very similar to boxing and unboxing |
288
|
|
|
of c#/java primitives. __set__ should take a "primitve" or "raw" value and create a "boxed" |
289
|
|
|
or "programatically useable" value of it. While __get__ should return the boxed value, |
290
|
|
|
dump in turn should unbox the value into a primitive or raw value. |
291
|
|
|
|
292
|
|
|
Arguments: |
293
|
|
|
types_ (primitive literal or type or sequence of types): |
294
|
|
|
default (any, callable, optional): If default is callable, it's guaranteed to return a |
295
|
|
|
valid value at the time of Entity creation. |
296
|
|
|
required (boolean, optional): |
297
|
|
|
validation (callable, optional): |
298
|
|
|
dump (boolean, optional): |
299
|
|
|
""" |
300
|
|
|
|
301
|
|
|
# Used to track order of field declarations. Supporting python 2.7, so can't rely |
302
|
|
|
# on __prepare__. Strategy lifted from http://stackoverflow.com/a/4460034/2127762 |
303
|
|
|
_order_helper = 0 |
304
|
|
|
|
305
|
|
|
def __init__(self, default=None, required=True, validation=None, in_dump=True, nullable=False): |
306
|
|
|
self._default = default if callable(default) else self.box(default) |
307
|
|
|
self._required = required |
308
|
|
|
self._validation = validation |
309
|
|
|
self._in_dump = in_dump |
310
|
|
|
self._nullable = nullable |
311
|
|
|
if default is not None: |
312
|
|
|
self.validate(self.box(maybecall(default))) |
313
|
|
|
|
314
|
|
|
self._order_helper = Field._order_helper |
315
|
|
|
Field._order_helper += 1 |
316
|
|
|
|
317
|
|
|
@property |
318
|
|
|
def name(self): |
319
|
|
|
try: |
320
|
|
|
return self._name |
321
|
|
|
except AttributeError: |
322
|
|
|
log.error("The name attribute has not been set for this field. " |
323
|
|
|
"Call set_name at class creation time.") |
324
|
|
|
raise |
325
|
|
|
|
326
|
|
|
def set_name(self, name): |
327
|
|
|
self._name = name |
328
|
|
|
return self |
329
|
|
|
|
330
|
|
|
def __get__(self, instance, instance_type): |
331
|
|
|
try: |
332
|
|
|
if instance is None: # if calling from the class object |
333
|
|
|
val = getattr(instance_type, KEY_OVERRIDES_MAP)[self.name] |
334
|
|
|
else: |
335
|
|
|
val = instance.__dict__[self.name] |
336
|
|
|
except AttributeError: |
337
|
|
|
log.error("The name attribute has not been set for this field.") |
338
|
|
|
raise AttributeError("The name attribute has not been set for this field.") |
339
|
|
|
except KeyError: |
340
|
|
|
if self.default is not None: |
341
|
|
|
val = maybecall(self.default) # default *can* be a callable |
342
|
|
|
elif self._nullable: |
343
|
|
|
return None |
344
|
|
|
else: |
345
|
|
|
raise AttributeError("A value for {0} has not been set".format(self.name)) |
346
|
|
|
if val is None and not self.nullable: |
347
|
|
|
# means the "tricky edge case" was activted in __delete__ |
348
|
|
|
raise AttributeError("The {0} field has been deleted.".format(self.name)) |
349
|
|
|
return self.unbox(val) |
350
|
|
|
|
351
|
|
|
def __set__(self, instance, val): |
352
|
|
|
# validate will raise an exception if invalid |
353
|
|
|
# validate will return False if the value should be removed |
354
|
|
|
instance.__dict__[self.name] = self.validate(self.box(val)) |
355
|
|
|
|
356
|
|
|
def __delete__(self, instance): |
357
|
|
|
if self.required: |
358
|
|
|
raise AttributeError("The {0} field is required and cannot be deleted." |
359
|
|
|
.format(self.name)) |
360
|
|
|
elif not self.nullable: |
361
|
|
|
# tricky edge case |
362
|
|
|
# given a field Field(default='some value', required=False, nullable=False) |
363
|
|
|
# works together with Entity.dump() logic for selecting fields to include in dump |
364
|
|
|
# `if value is not None or field.nullable` |
365
|
|
|
instance.__dict__[self.name] = None |
366
|
|
|
else: |
367
|
|
|
instance.__dict__.pop(self.name, None) |
368
|
|
|
|
369
|
|
|
def box(self, val): |
370
|
|
|
return val |
371
|
|
|
|
372
|
|
|
def unbox(self, val): |
373
|
|
|
return val |
374
|
|
|
|
375
|
|
|
def dump(self, val): |
376
|
|
|
return val |
377
|
|
|
|
378
|
|
|
def validate(self, val): |
379
|
|
|
""" |
380
|
|
|
|
381
|
|
|
Returns: |
382
|
|
|
True: if val is valid |
383
|
|
|
|
384
|
|
|
Raises: |
385
|
|
|
ValidationError |
386
|
|
|
""" |
387
|
|
|
# note here calling, but not assigning; could lead to unexpected behavior |
388
|
|
|
if isinstance(val, self._type) and (self._validation is None or self._validation(val)): |
389
|
|
|
return val |
390
|
|
|
elif val is None and self.nullable: |
391
|
|
|
return val |
392
|
|
|
raise ValidationError(getattr(self, 'name', 'undefined name'), val) |
393
|
|
|
|
394
|
|
|
@property |
395
|
|
|
def required(self): |
396
|
|
|
return self.is_required |
397
|
|
|
|
398
|
|
|
@property |
399
|
|
|
def is_required(self): |
400
|
|
|
return self._required |
401
|
|
|
|
402
|
|
|
@property |
403
|
|
|
def is_enum(self): |
404
|
|
|
return isinstance(self._type, type) and issubclass(self._type, Enum) |
405
|
|
|
|
406
|
|
|
@property |
407
|
|
|
def type(self): |
408
|
|
|
return self._type |
409
|
|
|
|
410
|
|
|
@property |
411
|
|
|
def default(self): |
412
|
|
|
return self._default |
413
|
|
|
|
414
|
|
|
@property |
415
|
|
|
def in_dump(self): |
416
|
|
|
return self._in_dump |
417
|
|
|
|
418
|
|
|
@property |
419
|
|
|
def nullable(self): |
420
|
|
|
return self.is_nullable |
421
|
|
|
|
422
|
|
|
@property |
423
|
|
|
def is_nullable(self): |
424
|
|
|
return self._nullable |
425
|
|
|
|
426
|
|
|
|
427
|
|
|
class BooleanField(Field): |
428
|
|
|
_type = bool |
429
|
|
|
|
430
|
|
|
def box(self, val): |
431
|
|
|
return None if val is None else bool(val) |
432
|
|
|
|
433
|
|
|
BoolField = BooleanField |
434
|
|
|
|
435
|
|
|
|
436
|
|
|
class IntegerField(Field): |
437
|
|
|
_type = integer_types |
438
|
|
|
|
439
|
|
|
IntField = IntegerField |
440
|
|
|
|
441
|
|
|
|
442
|
|
|
class NumberField(Field): |
443
|
|
|
_type = integer_types + (float, complex) |
444
|
|
|
|
445
|
|
|
|
446
|
|
|
class StringField(Field): |
447
|
|
|
_type = string_types |
448
|
|
|
|
449
|
|
|
|
450
|
|
|
class DateField(Field): |
451
|
|
|
_type = datetime |
452
|
|
|
|
453
|
|
|
def box(self, val): |
454
|
|
|
try: |
455
|
|
|
return dateparse(val) if isinstance(val, string_types) else val |
456
|
|
|
except ValueError as e: |
457
|
|
|
raise ValidationError(val, msg=e) |
458
|
|
|
|
459
|
|
|
def dump(self, val): |
460
|
|
|
return None if val is None else val.isoformat() |
461
|
|
|
|
462
|
|
|
|
463
|
|
|
class EnumField(Field): |
464
|
|
|
|
465
|
|
|
def __init__(self, enum_class, default=None, required=True, validation=None, |
466
|
|
|
in_dump=True, nullable=False): |
467
|
|
|
if not issubclass(enum_class, Enum): |
468
|
|
|
raise ValidationError(None, msg="enum_class must be an instance of Enum") |
469
|
|
|
self._type = enum_class |
470
|
|
|
super(self.__class__, self).__init__(default, required, validation, in_dump, nullable) |
471
|
|
|
|
472
|
|
|
def box(self, val): |
473
|
|
|
if val is None: |
474
|
|
|
# let the required/nullable logic handle validation for this case |
475
|
|
|
return None |
476
|
|
|
try: |
477
|
|
|
# try to box using val as an Enum name |
478
|
|
|
return val if isinstance(val, self._type) else self._type(val) |
479
|
|
|
except ValueError as e1: |
480
|
|
|
try: |
481
|
|
|
# try to box using val as an Enum value |
482
|
|
|
return self._type[val] |
483
|
|
|
except KeyError: |
484
|
|
|
raise ValidationError(val, msg=e1) |
485
|
|
|
|
486
|
|
|
def dump(self, val): |
487
|
|
|
return None if val is None else val.value |
488
|
|
|
|
489
|
|
|
|
490
|
|
|
class ListField(Field): |
491
|
|
|
_type = tuple |
492
|
|
|
|
493
|
|
|
def __init__(self, element_type, default=None, required=True, validation=None, |
494
|
|
|
in_dump=True, nullable=False): |
495
|
|
|
self._element_type = element_type |
496
|
|
|
super(self.__class__, self).__init__(default, required, validation, in_dump, nullable) |
497
|
|
|
|
498
|
|
|
def box(self, val): |
499
|
|
|
if val is None: |
500
|
|
|
return None |
501
|
|
|
elif isinstance(val, string_types): |
502
|
|
|
raise ValidationError("Attempted to assign a string to ListField {0}" |
503
|
|
|
"".format(self.name)) |
504
|
|
|
elif isinstance(val, Iterable): |
505
|
|
|
et = self._element_type |
506
|
|
|
if isinstance(et, type) and issubclass(et, Entity): |
507
|
|
|
return tuple(v if isinstance(v, et) else et(**v) for v in val) |
508
|
|
|
else: |
509
|
|
|
return tuple(val) |
510
|
|
|
else: |
511
|
|
|
raise ValidationError(val, msg="Cannot assign a non-iterable value to " |
512
|
|
|
"{0}".format(self.name)) |
513
|
|
|
|
514
|
|
|
def unbox(self, val): |
515
|
|
|
return tuple() if val is None and not self.nullable else val |
516
|
|
|
|
517
|
|
|
def dump(self, val): |
518
|
|
|
if isinstance(self._element_type, type) and issubclass(self._element_type, Entity): |
519
|
|
|
return tuple(v.dump() for v in val) |
520
|
|
|
else: |
521
|
|
|
return val |
522
|
|
|
|
523
|
|
|
def validate(self, val): |
524
|
|
|
if val is None: |
525
|
|
|
if not self.nullable: |
526
|
|
|
raise ValidationError(self.name, val) |
527
|
|
|
return None |
528
|
|
|
else: |
529
|
|
|
val = super(self.__class__, self).validate(val) |
530
|
|
|
et = self._element_type |
531
|
|
|
tuple(Raise(ValidationError(self.name, el, et)) for el in val |
532
|
|
|
if not isinstance(el, et)) |
533
|
|
|
return val |
534
|
|
|
|
535
|
|
|
|
536
|
|
|
class MapField(Field): |
537
|
|
|
_type = dict |
538
|
|
|
__eq__ = dict.__eq__ |
539
|
|
|
__hash__ = dict.__hash__ |
540
|
|
|
|
541
|
|
|
|
542
|
|
|
class ComposableField(Field): |
543
|
|
|
|
544
|
|
|
def __init__(self, field_class, default=None, required=True, validation=None, |
545
|
|
|
in_dump=True, nullable=False): |
546
|
|
|
self._type = field_class |
547
|
|
|
super(self.__class__, self).__init__(default, required, validation, in_dump, nullable) |
548
|
|
|
|
549
|
|
|
def box(self, val): |
550
|
|
|
if val is None: |
551
|
|
|
return None |
552
|
|
|
if isinstance(val, self._type): |
553
|
|
|
return val |
554
|
|
|
else: |
555
|
|
|
# assuming val is a dict now |
556
|
|
|
try: |
557
|
|
|
# if there is a key named 'self', have to rename it |
558
|
|
|
val['slf'] = val.pop('self') |
559
|
|
|
except KeyError: |
560
|
|
|
pass # no key of 'self', so no worries |
561
|
|
|
return val if isinstance(val, self._type) else self._type(**val) |
562
|
|
|
|
563
|
|
|
def dump(self, val): |
564
|
|
|
return None if val is None else val.dump() |
565
|
|
|
|
566
|
|
|
|
567
|
|
|
class EntityType(type): |
568
|
|
|
|
569
|
|
|
@staticmethod |
570
|
|
|
def __get_entity_subclasses(bases): |
571
|
|
|
try: |
572
|
|
|
return [base for base in bases if issubclass(base, Entity) and base is not Entity] |
573
|
|
|
except NameError: |
574
|
|
|
# NameError: global name 'Entity' is not defined |
575
|
|
|
return [] |
576
|
|
|
|
577
|
|
|
def __new__(mcs, name, bases, dct): |
578
|
|
|
# if we're about to mask a field that's already been created with something that's |
579
|
|
|
# not a field, then assign it to an alternate variable name |
580
|
|
|
non_field_keys = (key for key, value in items(dct) |
581
|
|
|
if not isinstance(value, Field) and not key.startswith('__')) |
582
|
|
|
entity_subclasses = EntityType.__get_entity_subclasses(bases) |
583
|
|
|
if entity_subclasses: |
584
|
|
|
keys_to_override = [key for key in non_field_keys |
585
|
|
|
if any(isinstance(base.__dict__.get(key), Field) |
586
|
|
|
for base in entity_subclasses)] |
587
|
|
|
dct[KEY_OVERRIDES_MAP] = {key: dct.pop(key) for key in keys_to_override} |
588
|
|
|
else: |
589
|
|
|
dct[KEY_OVERRIDES_MAP] = dict() |
590
|
|
|
|
591
|
|
|
return super(EntityType, mcs).__new__(mcs, name, bases, dct) |
592
|
|
|
|
593
|
|
|
def __init__(cls, name, bases, attr): |
594
|
|
|
super(EntityType, cls).__init__(name, bases, attr) |
595
|
|
|
cls.__fields__ = odict(cls.__fields__) if hasattr(cls, '__fields__') else odict() |
596
|
|
|
cls.__fields__.update(sorted(((name, field.set_name(name)) |
597
|
|
|
for name, field in cls.__dict__.items() |
598
|
|
|
if isinstance(field, Field)), |
599
|
|
|
key=lambda item: item[1]._order_helper)) |
600
|
|
|
if hasattr(cls, '__register__'): |
601
|
|
|
cls.__register__() |
602
|
|
|
|
603
|
|
|
@property |
604
|
|
|
def fields(cls): |
605
|
|
|
return cls.__fields__.keys() |
606
|
|
|
|
607
|
|
|
|
608
|
|
|
@with_metaclass(EntityType) |
609
|
|
|
class Entity(object): |
610
|
|
|
__fields__ = odict() |
611
|
|
|
|
612
|
|
|
def __init__(self, **kwargs): |
613
|
|
|
for key, field in items(self.__fields__): |
614
|
|
|
try: |
615
|
|
|
setattr(self, key, kwargs[key]) |
616
|
|
|
except KeyError: |
617
|
|
|
# handle the case of fields inherited from subclass but overrode on class object |
618
|
|
|
if key in getattr(self, KEY_OVERRIDES_MAP): |
619
|
|
|
setattr(self, key, getattr(self, KEY_OVERRIDES_MAP)[key]) |
620
|
|
|
elif field.required and field.default is None: |
621
|
|
|
raise ValidationError(key, msg="{0} requires a {1} field. Instantiated with " |
622
|
|
|
"{2}".format(self.__class__.__name__, |
623
|
|
|
key, kwargs)) |
624
|
|
|
except ValidationError: |
625
|
|
|
if kwargs[key] is not None or field.required: |
626
|
|
|
raise |
627
|
|
|
self.validate() |
628
|
|
|
self._initd = True |
629
|
|
|
|
630
|
|
|
@classmethod |
631
|
|
|
def create_from_objects(cls, *objects, **override_fields): |
632
|
|
|
init_vars = dict() |
633
|
|
|
search_maps = (AttrDict(override_fields), ) + objects |
634
|
|
|
for key, field in items(cls.__fields__): |
635
|
|
|
value = find_or_none(key, search_maps) |
636
|
|
|
if value is not None or field.required: |
637
|
|
|
init_vars[key] = field.type(value) if field.is_enum else value |
638
|
|
|
return cls(**init_vars) |
639
|
|
|
|
640
|
|
|
@classmethod |
641
|
|
|
def from_json(cls, json_str): |
642
|
|
|
return cls(**json_loads(json_str)) |
643
|
|
|
|
644
|
|
|
@classmethod |
645
|
|
|
def load(cls, data_dict): |
646
|
|
|
return cls(**data_dict) |
647
|
|
|
|
648
|
|
|
def validate(self): |
649
|
|
|
# TODO: here, validate should only have to determine if the required keys are set |
650
|
|
|
try: |
651
|
|
|
reduce(lambda x, y: y, (getattr(self, name) |
652
|
|
|
for name, field in self.__fields__.items() |
653
|
|
|
if field.required)) |
654
|
|
|
except AttributeError as e: |
655
|
|
|
raise ValidationError(None, msg=e) |
656
|
|
|
except TypeError as e: |
657
|
|
|
if "no initial value" in str(e): |
658
|
|
|
# TypeError: reduce() of empty sequence with no initial value |
659
|
|
|
pass |
660
|
|
|
else: |
661
|
|
|
raise # pragma: no cover |
662
|
|
|
|
663
|
|
|
def __repr__(self): |
664
|
|
|
def _valid(key): |
665
|
|
|
if key.startswith('_'): |
666
|
|
|
return False |
667
|
|
|
try: |
668
|
|
|
getattr(self, key) |
669
|
|
|
return True |
670
|
|
|
except AttributeError: |
671
|
|
|
return False |
672
|
|
|
|
673
|
|
|
def _val(key): |
674
|
|
|
val = getattr(self, key) |
675
|
|
|
return repr(val.value) if isinstance(val, Enum) else repr(val) |
676
|
|
|
|
677
|
|
|
def _sort_helper(key): |
678
|
|
|
field = self.__fields__.get(key) |
679
|
|
|
return field._order_helper if field is not None else -1 |
680
|
|
|
|
681
|
|
|
kwarg_str = ", ".join("{0}={1}".format(key, _val(key)) |
682
|
|
|
for key in sorted(self.__dict__, key=_sort_helper) |
683
|
|
|
if _valid(key)) |
684
|
|
|
return "{0}({1})".format(self.__class__.__name__, kwarg_str) |
685
|
|
|
|
686
|
|
|
@classmethod |
687
|
|
|
def __register__(cls): |
688
|
|
|
pass |
689
|
|
|
|
690
|
|
|
def json(self, indent=None, separators=None, **kwargs): |
691
|
|
|
return json_dumps(self.dump(), indent=indent, separators=separators, **kwargs) |
692
|
|
|
|
693
|
|
|
def pretty_json(self, indent=2, separators=(',', ': '), **kwargs): |
694
|
|
|
return self.json(indent=indent, separators=separators, **kwargs) |
695
|
|
|
|
696
|
|
|
def dump(self): |
697
|
|
|
return odict((field.name, field.dump(value)) |
698
|
|
|
for field, value in ((field, getattr(self, field.name, None)) |
699
|
|
|
for field in self.__dump_fields()) |
700
|
|
|
if value is not None or field.nullable) |
701
|
|
|
|
702
|
|
|
@classmethod |
703
|
|
|
def __dump_fields(cls): |
704
|
|
|
if '__dump_fields_cache' not in cls.__dict__: |
705
|
|
|
cls.__dump_fields_cache = tuple(field for field in values(cls.__fields__) |
706
|
|
|
if field.in_dump) |
707
|
|
|
return cls.__dump_fields_cache |
708
|
|
|
|
709
|
|
|
def __eq__(self, other): |
710
|
|
|
if self.__class__ != other.__class__: |
711
|
|
|
return False |
712
|
|
|
rando_default = 19274656290 # need an arbitrary but definite value if field does not exist |
713
|
|
|
return all(getattr(self, field, rando_default) == getattr(other, field, rando_default) |
714
|
|
|
for field in self.__fields__) |
715
|
|
|
|
716
|
|
|
def __hash__(self): |
717
|
|
|
return sum(hash(getattr(self, field, None)) for field in self.__fields__) |
718
|
|
|
|
719
|
|
|
|
720
|
|
|
class ImmutableEntity(Entity): |
721
|
|
|
|
722
|
|
|
def __setattr__(self, attribute, value): |
723
|
|
|
if getattr(self, '_initd', None): |
724
|
|
|
raise AttributeError("Assignment not allowed. {0} is immutable." |
725
|
|
|
.format(self.__class__.__name__)) |
726
|
|
|
super(ImmutableEntity, self).__setattr__(attribute, value) |
727
|
|
|
|
728
|
|
|
def __delattr__(self, item): |
729
|
|
|
if getattr(self, '_initd', None): |
730
|
|
|
raise AttributeError("Delete not allowed. {0} is immutable." |
731
|
|
|
.format(self.__class__.__name__)) |
732
|
|
|
super(ImmutableEntity, self).__delattr__(item) |
733
|
|
|
|