This repository has been archived by the owner on Apr 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
fields.py
1295 lines (1053 loc) · 37.8 KB
/
fields.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module contains field classes for use with `Models <serde.Model>`.
"""
import collections
import datetime
import re
import uuid
import isodate
from six import PY3, binary_type, integer_types, text_type
from six.moves.collections_abc import Mapping as MappingType
from serde.exceptions import ContextError, ValidationError
from serde.utils import is_subclass, try_lookup, zip_equal
def _resolve_to_field_instance(thing, none_allowed=True):
"""
Resolve an arbitrary object to a `Field` instance.
Args:
thing: anything to resolve to a `Field` instance.
none_allowed (bool): if set then a thing of `None` will be resolved to a
generic `Field`.
Returns:
Field: a field instance.
"""
# We import Model here to avoid circular dependency problems.
from serde.model import Model
# If the thing is None then return a generic Field instance.
if none_allowed and thing is None:
return Field()
# If the thing is a Field instance then thats great.
elif isinstance(thing, Field):
return thing
# If the thing is a subclass of Field then attempt to create an instance.
# This could fail the Field expects positional arguments.
if is_subclass(thing, Field):
return thing()
# If the thing is a subclass of Model then create a Nested instance.
if is_subclass(thing, Model):
return Nested(thing)
# If the thing is a built-in type that we support then create an Instance
# with that type.
field_class = FIELD_CLASS_MAP.get(thing, None)
if field_class is not None:
return field_class()
raise TypeError('failed to resolve {!r} into a field'.format(thing))
class BaseField(object):
"""
A base field or tag on a `~serde.Model`.
Fields and tags handle serializing and deserializing of input values for
models. This class serves as a base class for both fields and tags.
Args:
serializers (list): a list of serializer functions taking the value to
serialize as an argument. The functions need to raise an `Exception`
if they fail. These serializer functions will be applied before the
primary serializer on this base field.
deserializers (list): a list of deserializer functions taking the value
to deserialize as an argument. The functions need to raise an
`Exception` if they fail. These deserializer functions will be
applied after the primary deserializer on this base field.
"""
# This is so we can get the order the bases were instantiated in.
_counter = 1
def __init__(self, serializers=None, deserializers=None):
"""
Create a new base field.
"""
self.id = BaseField._counter
BaseField._counter += 1
self.serializers = serializers or []
self.deserializers = deserializers or []
def __eq__(self, other):
"""
Whether two base fields are the same.
"""
return isinstance(other, self.__class__) and self._attrs() == other._attrs()
@property
def __model__(self):
"""
The model class that the base field is bound to.
"""
return self._model_cls
def _attrs(self):
"""
Returns a dictionary of all public attributes on this base field.
"""
return {
name: value
for name, value in vars(self).items()
if name not in ('id', '_model_cls')
}
def _bind(self, model_cls):
"""
Bind the base field to a model class.
"""
if hasattr(self, '_model_cls'):
raise ContextError(
'attempted to use {!r} instance more than once'.format(
self.__class__.__name__
)
)
self._model_cls = model_cls
def _serialize_with(self, model, d):
"""
Serialize value(s) from a model instance to a dictionary.
This method needs to be overridden and should use ``self._serialize()``
on individual values.
Args:
model (Model): the model instance that we are serializing from.
d (dict): the dictionary to serialize to.
Returns:
dict: the updated dictionary to continue serializing to.
"""
raise NotImplementedError('this method should be overridden')
def _deserialize_with(self, model, d):
"""
Deserialize value(s) from a dictionary to a model instance.
This method needs to be overridden and should use
``self._deserialize()`` on individual values.
Args:
model (Model): the model instance that we are deserializing to.
d (dict): the dictionary to deserialize from.
Returns:
(model, dict): the updated Model instance to continue deserializing
to and the updated dictionary to continue deserializing from.
"""
raise NotImplementedError('this method should be overridden')
def _serialize(self, value):
for serializer in self.serializers:
value = serializer(value)
return self.serialize(value)
def _deserialize(self, value):
value = self.deserialize(value)
for deserializer in self.deserializers:
value = deserializer(value)
return value
def serialize(self, value):
"""
Serialize a value according to this base field's specification.
"""
return value
def deserialize(self, value):
"""
Deserialize a value according to this base field's specification.
"""
return value
class Field(BaseField):
"""
A field on a `~serde.Model`.
Fields handle serializing, deserializing, normalization, and validation of
input values for `~serde.Model` objects.
Args:
rename (str): override the name for the field when serializing and
expect this name when deserializing.
default: a value to use if there is no input field value or the input
value is `None`. This can also be a callable that generates the
default. The callable must take no positional arguments. This
default only applies to instantiated values. Field values are still
required on deserialization.
serializers (list): a list of serializer functions taking the value to
serialize as an argument. The functions need to raise an `Exception`
if they fail. These serializer functions will be applied before the
primary serializer on this Field.
deserializers (list): a list of deserializer functions taking the value
to deserialize as an argument. The functions need to raise an
`Exception` if they fail. These deserializer functions will be
applied after the primary deserializer on this Field.
normalizers (list): a list of normalizer functions taking the value to
normalize as an argument. The functions need to raise an `Exception`
if they fail. These normalizer functions will be applied after the
primary normalizer on this Field.
validators (list): a list of validator functions taking the value to
validate as an argument. The functions need to raise an `Exception`
if they fail.
"""
def __init__(
self,
rename=None,
default=None,
serializers=None,
deserializers=None,
normalizers=None,
validators=None,
):
"""
Create a new `Field`.
"""
super(Field, self).__init__(
serializers=serializers, deserializers=deserializers
)
self.rename = rename
self.default = default
self.normalizers = normalizers or []
self.validators = validators or []
def _attrs(self):
"""
Returns a dictionary of all public attributes on this field.
"""
return {
name: value
for name, value in vars(self).items()
if name not in ('id', '_model_cls', '_attr_name', '_serde_name')
}
def _default(self):
"""
Call the default function or return the default value.
"""
return self.default() if callable(self.default) else self.default
def _bind(self, model_cls, name):
"""
Bind the field to a model class with an attribute name.
"""
super(Field, self)._bind(model_cls)
self._attr_name = name
self._serde_name = self.rename if self.rename else name
def _instantiate_with(self, model, kwargs):
"""
Instantiate the corresponding model attribute from the keyword args.
This method should .pop() from kwargs.
"""
value = self._instantiate(kwargs.pop(self._attr_name, None))
if value is None:
raise TypeError(
'__init__() missing required argument {!r}'.format(self._attr_name)
)
setattr(model, self._attr_name, value)
def _serialize_with(self, model, d):
"""
Serialize the corresponding model attribute to a dictionary.
"""
d[self._serde_name] = self._serialize(getattr(model, self._attr_name))
return d
def _deserialize_with(self, model, d):
"""
Deserialize the corresponding model attribute from a dictionary.
"""
try:
value = d[self._serde_name]
except KeyError:
raise ValidationError(
'missing data, expected field {!r}'.format(self._serde_name)
)
setattr(model, self._attr_name, self._deserialize(value))
return model, d
def _normalize_with(self, model):
"""
Normalize the model attribute according to this field's specification.
"""
value = getattr(model, self._attr_name)
setattr(model, self._attr_name, self._normalize(value))
def _validate_with(self, model):
"""
Validate the model attribute according to this field's specification.
"""
self._validate(getattr(model, self._attr_name))
def _instantiate(self, value):
return self._default() if value is None else value
def _normalize(self, value):
value = self.normalize(value)
for normalizer in self.normalizers:
value = normalizer(value)
return value
def _validate(self, value):
self.validate(value)
for validator in self.validators:
validator(value)
def normalize(self, value):
"""
Normalize a value according to this field's specification.
By default this method does not do anything.
"""
return value
def validate(self, value):
"""
Validate a value according to this field's specification.
By default this method does not do anything.
"""
pass
class Optional(Field):
"""
An optional field.
An `Optional` is a field that is allowed to be `None`. Serialization,
normalization, deserialization, and validation using the wrapped field will
only be called if the value is not `None`.
Args:
inner: the `Field` class/instance that this `Optional` wraps.
default: a value to use if there is no input field value or the input
value is `None`. This can also be a callable that generates the
default. The callable must take no positional arguments.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, inner=None, **kwargs):
"""
Create a new `Optional`.
"""
super(Optional, self).__init__(**kwargs)
self.inner = _resolve_to_field_instance(inner)
def _instantiate_with(self, model, kwargs):
"""
Instantiate the corresponding model attribute from the keyword args.
This method should .pop() from kwargs.
"""
name = self._attr_name
setattr(model, name, self._instantiate(kwargs.pop(name, None)))
def _serialize_with(self, model, d):
"""
Serialize the corresponding model attribute to a dictionary.
The value will only be added to the dictionary if it is not `None`.
"""
value = self._serialize(getattr(model, self._attr_name))
if value is not None:
d[self._serde_name] = value
return d
def _deserialize_with(self, model, d):
"""
Deserialize the corresponding model attribute from a dictionary.
If the field is not present in the dictionary then the model instance is
left unchanged.
"""
try:
value = d[self._serde_name]
except KeyError:
return model, d
setattr(model, self._attr_name, self._deserialize(value))
return model, d
def _normalize_with(self, model):
"""
Normalize the model attribute.
"""
value = self._normalize(getattr(model, self._attr_name, None))
setattr(model, self._attr_name, value)
def _instantiate(self, value):
return value
def _serialize(self, value):
if value is not None:
value = self.serialize(value)
for serializer in self.serializers:
value = serializer(value)
return value
def _deserialize(self, value):
if value is not None:
value = self.deserialize(value)
for deserializer in self.deserializers:
value = deserializer(value)
return value
def _normalize(self, value):
if value is not None:
value = self.normalize(value)
for normalizer in self.normalizers:
value = normalizer(value)
else:
value = self._default()
return value
def _validate(self, value):
if value is not None:
self.validate(value)
for validator in self.validators:
validator(value)
def serialize(self, value):
"""
Serialize the given value using the inner `Field`.
"""
return self.inner._serialize(value)
def deserialize(self, value):
"""
Deserialize the given value using the inner `Field`.
"""
return self.inner._deserialize(value)
def normalize(self, value):
"""
Normalize the given value using the inner `Field`.
"""
return self.inner._normalize(value)
def validate(self, value):
"""
Validate the given value using the inner `Field`.
"""
self.inner._validate(value)
class Instance(Field):
"""
A field that is an instance of a type.
An `Instance` field simply validates that the data is the specified type.
Args:
type: the type that this `Instance` wraps.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, ty, **kwargs):
"""
Create a new `Instance`.
"""
super(Instance, self).__init__(**kwargs)
self.ty = ty
def validate(self, value):
"""
Validate the given value is an instance of the specified type.
"""
if not isinstance(value, self.ty):
raise ValidationError(
'invalid type, expected {!r}'.format(self.ty.__name__), value=value
)
class Nested(Instance):
"""
A field for `~serde.Model` fields.
A `Nested` is a wrapper field for models to support sub-models. The
serialize and deserialize methods call the `~serde.Model.to_dict()` and
`~serde.Model.from_dict()` methods on the model class. This allows complex
nested models.
Args:
model_cls (serde.Model): the nested model class.
**kwargs: keyword arguments for the `Field` constructor.
"""
def serialize(self, model):
"""
Serialize the given `~serde.Model` instance as a dictionary.
"""
return model.to_dict()
def deserialize(self, d):
"""
Deserialize the given dictionary to a `~serde.Model` instance.
"""
if not isinstance(d, MappingType):
raise ValidationError("invalid type, expected 'mapping'", value=d)
return self.ty.from_dict(d)
class Flatten(Nested):
"""
A field that flattens the serialized version of the wrapped `~serde.Model`
into the parent dictionary.
This effectively removes one level of structure between the serialized
representation and the Python model representation.
Warning:
this field cannot be contained by another like an `Optional`, or a
`List` or `Dict`.
Args:
model_cls (serde.Model): the nested model class.
**kwargs: keyword arguments for the `Field` constructor.
"""
def _serialize_with(self, model, d):
"""
Serialize the corresponding nested model attribute to a dictionary.
"""
d.update(self._serialize(getattr(model, self._attr_name)))
return d
def _deserialize_with(self, model, d):
"""
Deserialize the corresponding model attribute from a dictionary.
"""
setattr(model, self._attr_name, self._deserialize(d))
return model, d
class _Container(Instance):
"""
A base class for `Dict`, `List`, `Tuple`, and other container fields.
"""
def __init__(self, ty, **kwargs):
"""
Create a new `_Container`.
"""
super(_Container, self).__init__(ty, **kwargs)
self.kwargs = {}
def _iter(self, value):
"""
Iterate over the container.
"""
raise NotImplementedError()
def _apply(self, stage, element):
"""
Apply a stage to a particular element in the container.
"""
return getattr(self.element, stage)(element)
def serialize(self, value):
"""
Serialize the given container.
Each element in the container will be serialized with the specified
field instances.
"""
value = self.ty(
(self._apply('_serialize', element) for element in self._iter(value)),
**self.kwargs
)
return super(_Container, self).serialize(value)
def deserialize(self, value):
"""
Deserialize the given container.
Each element in the container will be deserialized with the specified
field instances.
"""
value = super(_Container, self).deserialize(value)
return self.ty(
(self._apply('_deserialize', element) for element in self._iter(value)),
**self.kwargs
)
def normalize(self, value):
"""
Deserialize the given container.
Each element in the container will be normalized with the specified
field instances.
"""
value = super(_Container, self).normalize(value)
return self.ty(
(self._apply('_normalize', element) for element in self._iter(value)),
**self.kwargs
)
def validate(self, value):
"""
Validate the given container.
Each element in the container will be validated with the specified field
instances.
"""
super(_Container, self).validate(value)
for element in self._iter(value):
self._apply('_validate', element)
class _Mapping(_Container):
"""
A mapping field to be used as the base class for `Dict` and `OrderedDict`.
"""
def __init__(self, ty, key=None, value=None, **kwargs):
super(_Mapping, self).__init__(ty, **kwargs)
self.key = _resolve_to_field_instance(key)
self.value = _resolve_to_field_instance(value)
def _iter(self, value):
"""
Iterate over the mapping's items.
"""
try:
for element in value.items():
yield element
except (AttributeError, TypeError):
raise ValidationError(
'invalid type, expected {!r}'.format(self.ty.__name__), value=value
)
def _apply(self, stage, element):
"""
Apply the key stage to each key, and the value stage to each value.
"""
k, v = element
return (getattr(self.key, stage)(k), getattr(self.value, stage)(v))
class Dict(_Mapping):
"""
This field represents the built-in `dict` type.
Args:
key: the `Field` class or instance for keys in this `Dict`.
value: the `Field` class or instance for values in this `Dict`.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, key=None, value=None, **kwargs):
"""
Create a new `Dict`.
"""
super(Dict, self).__init__(dict, key=key, value=value, **kwargs)
class OrderedDict(_Mapping):
"""
An `~collections.OrderedDict` field.
Args:
key: the `Field` class or instance for keys in this `OrderedDict`.
value: the `Field` class or instance for values in this `OrderedDict`.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, key=None, value=None, **kwargs):
"""
Create a new `OrderedDict`.
"""
super(OrderedDict, self).__init__(
collections.OrderedDict, key=key, value=value, **kwargs
)
class _Sequence(_Container):
"""
A sequence field to be used as the base class for fields such as `List` and `Set`
"""
def __init__(self, ty, element=None, **kwargs):
super(_Sequence, self).__init__(ty, **kwargs)
self.element = _resolve_to_field_instance(element)
def _iter(self, value):
"""
Iterate over the sequence.
"""
try:
for element in value:
yield element
except TypeError:
raise ValidationError(
'invalid type, expected {!r}'.format(self.ty.__name__), value=value
)
class Deque(_Sequence):
"""
A `~collections.deque` field.
Args:
element: the `Field` class or instance for elements in the `Deque`.
maxlen (int): the maximum length of this `Deque`.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, element=None, maxlen=None, **kwargs):
"""
Create a new `Deque`.
"""
super(Deque, self).__init__(collections.deque, element=element, **kwargs)
self.kwargs = {'maxlen': maxlen}
@property
def maxlen(self):
"""
The maximum length of this `Deque`.
"""
return self.kwargs['maxlen']
def validate(self, value):
"""
Validate the given deque.
"""
super(Deque, self).validate(value)
if value.maxlen != self.maxlen:
raise ValidationError(
'invalid max length, expected {}'.format(self.maxlen), value=value
)
class FrozenSet(_Sequence):
"""
This field represents the built-in `frozenset` type.
Args:
element: the `Field` class or instance for elements in the `Set`.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, element=None, **kwargs):
"""
Create a new `FrozenSet`.
"""
super(FrozenSet, self).__init__(frozenset, element=element, **kwargs)
class List(_Sequence):
"""
This field represents the built-in `list` type.
Args:
element: the `Field` class or instance for elements in the `List`.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, element=None, **kwargs):
"""
Create a new `List`.
"""
super(List, self).__init__(list, element=element, **kwargs)
class Set(_Sequence):
"""
This field represents the built-in `set` type.
Args:
element: the `Field` class or instance for elements in the `Set`.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, element=None, **kwargs):
"""
Create a new `Set`.
"""
super(Set, self).__init__(set, element=element, **kwargs)
class Tuple(_Sequence):
"""
This field represents the built-in `tuple` type.
Args:
*elements: the `Field` classes or instances for elements in this tuple.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, *elements, **kwargs):
"""
Create a new `Tuple`.
"""
super(_Sequence, self).__init__(tuple, **kwargs)
self.elements = tuple(
_resolve_to_field_instance(e, none_allowed=False) for e in elements
)
assert not hasattr(self, 'element')
def _iter(self, value):
"""
Iterate over the fields and each element in the tuple.
"""
return zip_equal(self.elements, super(Tuple, self)._iter(value))
def _apply(self, stage, element):
"""
Apply the element field stage to the corresponding element value.
"""
f, v = element
return getattr(f, stage)(v)
def create_primitive(name, ty):
"""
Create a primitive `Field` class.
"""
doc = """\
This field represents the built-in `{ty}` type.
Args:
**kwargs: keyword arguments for the `Field` constructor.
""".format(
ty=ty
)
def __init__(self, **kwargs): # noqa: N807
Instance.__init__(self, ty, **kwargs)
__init__.__doc__ = 'Create a new `{name}`.'.format(name=name)
return type(name, (Instance,), {'__doc__': doc, '__init__': __init__})
Bool = create_primitive('Bool', bool)
Complex = create_primitive('Complex', complex)
Float = create_primitive('Float', float)
Int = create_primitive('Int', int)
Str = create_primitive('Str', str)
Bytes = create_primitive('Bytes', bytes) if bytes != str else Str
try:
BaseString = create_primitive('BaseString', basestring)
except NameError:
pass
try:
Long = create_primitive('Long', long)
except NameError:
pass
try:
Unicode = create_primitive('Unicode', unicode)
except NameError:
pass
del create_primitive
class Literal(Field):
"""
A literal field.
A `Literal` is a field that always has to be the specified value.
Args:
value: the value that this `Literal` wraps.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, value, **kwargs):
"""
Create a new `Literal`.
"""
super(Literal, self).__init__(**kwargs)
self.value = value
def validate(self, value):
"""
Validate that the given value is equal to the value.
"""
if value != self.value:
raise ValidationError(
'invalid literal, expected {!r}'.format(self.value), value=value
)
class Constant(Literal):
"""
Deprecated, use `Literal`.
"""
def __init__(self, value, **kwargs):
"""
Create a new `Constant`.
"""
super(Constant, self).__init__(value, **kwargs)
class Choice(Field):
"""
One of a given selection of values.
A `Choice` field checks if the input data is one of the allowed values.
These values do not need to be the same type.
Args:
choices: a list or range or tuple of allowed values.
**kwargs: keyword arguments for the `Field` constructor.
"""
def __init__(self, choices, **kwargs):
"""
Create a new `Choice`.
"""
super(Choice, self).__init__(**kwargs)
self.choices = choices
def validate(self, value):
"""
Validate that the given value is one of the choices.
"""
super(Choice, self).validate(value)
if value not in self.choices:
raise ValidationError('invalid choice', value=value)
class DateTime(Instance):
"""
A `~datetime.datetime` field.
This field serializes `~datetime.datetime` objects as strings and
deserializes string representations of datetimes as `~datetime.datetime`
objects.
The date format can be specified. It will default to ISO 8601.
Args:
format (str): the datetime format to use. "iso8601" may be used for
ISO 8601 datetimes.
**kwargs: keyword arguments for the `Field` constructor.
"""
ty = datetime.datetime
def __init__(self, format='iso8601', **kwargs):
"""
Create a new `DateTime`.
"""
super(DateTime, self).__init__(self.__class__.ty, **kwargs)
self.format = format
def serialize(self, value):
"""
Serialize the given `~datetime.datetime` as a string.
"""
if self.format == 'iso8601':
return value.isoformat()
else:
return value.strftime(self.format)
def deserialize(self, value):
"""
Deserialize the given string as a `~datetime.datetime`.
"""
if self.format == 'iso8601':
try:
return isodate.parse_datetime(value)
except isodate.ISO8601Error:
raise ValidationError('invalid ISO 8601 datetime', value=value)
else:
try:
return datetime.datetime.strptime(value, self.format)
except (TypeError, ValueError):
raise ValidationError(
'invalid datetime, expected format {!r}'.format(self.format),
value=value,
)
class Date(DateTime):
"""
A `~datetime.date` field.
This field behaves in a similar fashion to the `DateTime` field.
"""
ty = datetime.date
def deserialize(self, value):