/
fields.py
1518 lines (1283 loc) · 57.2 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
# -*- coding: utf-8 -*-
"""Field classes for various types of data.
"""
from __future__ import absolute_import, unicode_literals
import datetime as dt
import uuid
import warnings
import decimal
from operator import attrgetter
from marshmallow import validate, utils, class_registry
from marshmallow.base import FieldABC, SchemaABC
from marshmallow.compat import text_type, iteritems, total_seconds, basestring
from marshmallow.exceptions import (
MarshallingError,
UnmarshallingError,
ForcedError,
RegistryError,
ValidationError,
)
__all__ = [
'Marshaller',
'Unmarshaller',
'Field',
'Raw',
'Nested',
'List',
'String',
'UUID',
'Number',
'Integer',
'Decimal',
'Boolean',
'FormattedString',
'Float',
'Arbitrary',
'DateTime',
'LocalDateTime',
'Time',
'Date',
'TimeDelta',
'Fixed',
'Price',
'Url',
'URL',
'Email',
'Method',
'Function',
'Select',
'QuerySelect',
'QuerySelectList',
'Enum',
'Str',
'Bool',
'Int',
'null',
'missing',
]
class _Null(object):
def __bool__(self):
return False
__nonzero__ = __bool__ # PY2 compat
def __repr__(self):
return '<marshmallow.fields.null>'
class _Missing(_Null):
def __repr__(self):
return '<marshmallow.fields.missing>'
# Singleton that represents an empty value. Used as the default for Nested
# fields so that `Field._call_with_validation` is invoked, even when the
# object to serialize has the nested attribute set to None. Therefore,
# `RegistryErrors` are properly raised.
null = _Null()
# Singleton value that indicates that a field's value is missing from input
# dict passed to :meth:`Schema.load`. If the field's value is not required,
# it's ``default`` value is used.
missing = _Missing()
def _call_and_store(getter_func, data, field_name, field_obj, errors_dict,
exception_class, strict=False):
"""Helper method for DRYing up logic in the :meth:`Marshaller.serialize` and
:meth:`UnMarshaller.deserialize` methods. Call ``getter_func`` with ``data`` as its
argument, and store any errors of type ``exception_class`` in ``error_dict``.
:param callable getter_func: Function for getting the serialized/deserialized
value from ``data``.
:param data: The data passed to ``getter_func``.
:param str field_name: Field name.
:param FieldABC field_obj: Field object that performs the
serialization/deserialization behavior.
:param dict errors_dict: Dictionary to store errors on.
:param type exception_class: Exception class that will be caught during
serialization/deserialization. Errors of this type will be stored
in ``errors_dict``.
"""
try:
value = getter_func(data)
except RegistryError:
raise
except exception_class as err: # Store errors
if strict:
err.field = field_obj
err.field_name = field_name
raise err
# Warning: Mutation!
if (hasattr(err, 'underlying_exception') and
isinstance(err.underlying_exception, ValidationError)):
validation_error = err.underlying_exception
if isinstance(validation_error.messages, dict):
errors_dict[field_name] = validation_error.messages
else:
errors_dict.setdefault(field_name, []).extend(validation_error.messages)
else:
errors_dict.setdefault(field_name, []).append(text_type(err))
value = None
except TypeError:
# field declared as a class, not an instance
if (isinstance(field_obj, type) and
issubclass(field_obj, FieldABC)):
msg = ('Field for "{0}" must be declared as a '
'Field instance, not a class. '
'Did you mean "fields.{1}()"?'
.format(field_name, field_obj.__name__))
raise TypeError(msg)
raise
return value
class Marshaller(object):
"""Callable class responsible for serializing data and storing errors.
:param str prefix: Optional prefix that will be prepended to all the
serialized field names.
"""
def __init__(self, prefix=''):
self.prefix = prefix
#: Dictionary of errors stored during serialization
self.errors = {}
#: True while serializing a collection
self.__pending = False
def serialize(self, obj, fields_dict, many=False, strict=False, skip_missing=False,
accessor=None, dict_class=None):
"""Takes raw data (a dict, list, or other object) and a dict of
fields to output and serializes the data based on those fields.
:param obj: The actual object(s) from which the fields are taken from
:param dict fields_dict: Mapping of field names to :class:`Field` objects.
:param bool many: Set to `True` if ``data`` should be serialized as
a collection.
:param bool strict: If `True`, raise errors if invalid data are passed in
instead of failing silently and storing the errors.
:param skip_missing: If `True`, skip key:value pairs when ``value`` is `None`.
:param callable accessor: Function to use for getting values from ``obj``.
:param type dict_class: Dictionary class used to construct the output.
:return: A dictionary of the marshalled data
.. versionchanged:: 1.0.0
Renamed from ``marshal``.
"""
dict_class = dict_class or dict
# Reset errors dict if not serializing a collection
if not self.__pending:
self.errors = {}
if many and obj is not None:
self.__pending = True
ret = [self.serialize(d, fields_dict, many=False, strict=strict,
dict_class=dict_class)
for d in obj]
self.__pending = False
return ret
items = []
for attr_name, field_obj in iteritems(fields_dict):
key = ''.join([self.prefix, attr_name])
getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
value = _call_and_store(
getter_func=getter,
data=obj,
field_name=key,
field_obj=field_obj,
errors_dict=self.errors,
exception_class=MarshallingError,
strict=strict
)
skip_conds = (
field_obj.load_only,
value is missing,
skip_missing and value in field_obj.SKIPPABLE_VALUES,
)
if any(skip_conds):
continue
items.append((key, value))
return dict_class(items)
# Make an instance callable
__call__ = serialize
class Unmarshaller(object):
"""Callable class responsible for deserializing data and storing errors.
.. versionadded:: 1.0.0
"""
def __init__(self):
#: Dictionary of errors stored during deserialization
self.errors = {}
#: True while deserializing a collection
self.__pending = False
def _validate(self, validators, output, fields_dict, strict=False):
"""Perform schema-level validation. Stores errors if ``strict`` is `False`.
"""
for validator_func in validators:
try:
if validator_func(output) is False:
func_name = utils.get_callable_name(validator_func)
raise ValidationError('Schema validator {0}({1}) is False'.format(
func_name, dict(output)
))
except ValidationError as err:
# Store or reraise errors
if err.fields:
field_names = err.fields
field_objs = [fields_dict[each] for each in field_names]
else:
field_names = ['_schema']
field_objs = []
if strict:
raise UnmarshallingError(err, fields=field_objs,
field_names=field_names)
for field_name in field_names:
if isinstance(err.messages, (list, tuple)):
self.errors.setdefault(field_name, []).extend(err.messages)
elif isinstance(err.messages, dict):
self.errors.setdefault(field_name, []).append(err.messages)
else:
self.errors.setdefault(field_name, []).append(text_type(err))
return output
def deserialize(self, data, fields_dict, many=False, validators=None,
preprocess=None, postprocess=None, strict=False, dict_class=dict):
"""Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict fields_dict: Mapping of field names to :class:`Field` objects.
:param bool many: Set to `True` if ``data`` should be deserialized as
a collection.
:param list validators: List of validation functions to apply to the
deserialized dictionary.
:param list preprocess: List of pre-processing functions.
:param list postprocess: List of post-processing functions.
:param bool strict: If `True`, raise errors if invalid data are passed in
instead of failing silently and storing the errors.
:param type dict_class: Dictionary class used to construct the output.
:return: A dictionary of the deserialized data.
"""
# Reset errors if not deserializing a collection
if not self.__pending:
self.errors = {}
if many and data is not None:
self.__pending = True
ret = [self.deserialize(d, fields_dict, many=False,
validators=validators, preprocess=preprocess,
postprocess=postprocess, strict=strict, dict_class=dict_class)
for d in data]
self.__pending = False
return ret
if data is not None:
items = []
for attr_name, field_obj in iteritems(fields_dict):
if attr_name not in fields_dict:
continue
if field_obj.dump_only:
continue
key = fields_dict[attr_name].attribute or attr_name
raw_value = data.get(attr_name, missing)
if raw_value is missing and field_obj.load_from:
raw_value = data.get(field_obj.load_from, missing)
if raw_value is missing and field_obj.missing is not null:
_miss = field_obj.missing
raw_value = _miss() if callable(_miss) else _miss
if raw_value is missing and not field_obj.required:
continue
value = _call_and_store(
getter_func=field_obj.deserialize,
data=raw_value,
field_name=key,
field_obj=field_obj,
errors_dict=self.errors,
exception_class=UnmarshallingError,
strict=strict
)
if raw_value is not missing:
items.append((key, value))
ret = dict_class(items)
else:
ret = None
if preprocess:
preprocess = preprocess or []
for func in preprocess:
ret = func(ret)
if validators:
validators = validators or []
ret = self._validate(validators, ret, fields_dict=fields_dict, strict=strict)
if postprocess:
postprocess = postprocess or []
for func in postprocess:
ret = func(ret)
return ret
# Make an instance callable
__call__ = deserialize
class Field(FieldABC):
"""Basic field from which other fields should extend. It applies no
formatting by default, and should only be used in cases where
data does not need to be formatted before being serialized or deserialized.
:param default: Default serialization value for the field if the attribute is
`None`. May be a value or a callable.
:param str attribute: The name of the attribute to get the value from. If
`None`, assumes the attribute has the same name as the field.
:param str load_from: Additional key to look for when deserializing. Will only
be checked if the field's name is not found on the input dictionary.
:param str error: Error message stored upon validation failure.
:param callable validate: Validator or collection of validators that are called
during deserialization. Validator takes a field's input value as
its only parameter and returns a boolean.
If it returns `False`, an :exc:`UnmarshallingError` is raised.
:param required: Raise an :exc:`UnmarshallingError` if the field value
is not supplied during deserialization. If not a `bool`(e.g. a `str`),
the provided value will be used as the message of the
:exc:`ValidationError` instead of the default message.
:param allow_none: Set to `True` if `None` should be considered a valid value during
validation/deserialization. If not a `bool` (e.g. a `str`), the provided
value will be used as the message of the :exc:`ValidationError` instead
of the default message.
:param bool load_only: If `True` skip this field during serialization, otherwise
its value will be present in the serialized data.
:param bool dump_only: If `True` skip this field during deserialization, otherwise
its value will be present in the deserialized object. In the context of an
HTTP API, this effectively marks the field as "read-only".
:param missing: Default deserialization value for the field if the field is not
found in the input data. May be a value or a callable.
:param metadata: Extra arguments to be stored as metadata.
.. versionchanged:: 1.0.0
Deprecated `error` parameter. Raise a :exc:`marshmallow.ValidationError` instead.
.. versionchanged:: 2.0.0
Added `allow_none` parameter, which makes validation/deserialization of `None`
consistent across fields.
.. versionchanged:: 2.0.0
Added `load_only` and `dump_only` parameters, which allow field skipping
during the (de)serialization process.
.. versionchanged:: 2.0.0
Added `missing` parameter, which indicates the value for a field if the field
is not found during deserialization.
"""
# Some fields, such as Method fields and Function fields, are not expected
# to exists as attributes on the objects to serialize. Set this to False
# for those fields
_CHECK_ATTRIBUTE = True
_creation_index = 0
#: Values that are skipped by `Marshaller` if ``skip_missing=True``
SKIPPABLE_VALUES = (None, )
def __init__(self, default=None, attribute=None, load_from=None, error=None,
validate=None, required=False, allow_none=False, load_only=False,
dump_only=False, missing=null, **metadata):
self.default = default
self.attribute = attribute
self.load_from = load_from # this flag is used by Unmarshaller
if error:
warnings.warn('The error parameter is deprecated. Raise a '
'marshmallow.ValidationError in your validators '
'instead.', category=DeprecationWarning)
self.error = error
self.validate = validate
if utils.is_iterable_but_not_string(validate):
if not utils.is_generator(validate):
self.validators = validate
else:
self.validators = list(validate)
elif callable(validate):
self.validators = [validate]
elif validate is None:
self.validators = []
else:
raise ValueError("The 'validate' parameter must be a callable "
"or a collection of callables.")
self.required = required
self.allow_none = allow_none
self.load_only = load_only
self.dump_only = dump_only
self.missing = missing
self.metadata = metadata
self._creation_index = Field._creation_index
Field._creation_index += 1
self.parent = FieldABC.parent
def __repr__(self):
return ('<fields.{ClassName}(default={self.default!r}, '
'attribute={self.attribute!r}, error={self.error!r}, '
'validate={self.validate}, required={self.required})>'
.format(ClassName=self.__class__.__name__, self=self))
def get_value(self, attr, obj, accessor=None):
"""Return the value for a given key from an object."""
# NOTE: Use getattr instead of direct attribute access here so that
# subclasses aren't required to define `attribute` member
attribute = getattr(self, 'attribute', None)
accessor_func = accessor or utils.get_value
check_key = attr if attribute is None else attribute
return accessor_func(check_key, obj)
def _validate(self, value):
"""Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
does not succeed.
"""
errors = []
for validator in self.validators:
func_name = utils.get_callable_name(validator)
msg = 'Validator {0}({1}) is False'.format(
func_name, value
)
try:
if validator(value) is False:
raise ValidationError(getattr(self, 'error', None) or msg)
except ValidationError as err:
if isinstance(err.messages, dict):
errors.append(err.messages)
else:
errors.extend(err.messages)
if errors:
raise ValidationError(errors)
def _call_and_reraise(self, func, exception_class):
"""Utility method to invoke a function and raise ``exception_class`` if an error
occurs.
:param callable func: Function to call. Must take no arguments.
:param Exception exception_class: Type of exception to raise when an error occurs.
"""
try:
return func()
# TypeErrors should be raised if fields are not declared as instances
except TypeError:
raise
# Raise ForcedErrors
except ForcedError as err:
if err.underlying_exception:
raise err.underlying_exception
else:
raise err
except ValidationError as err:
raise exception_class(err)
# Reraise errors, wrapping with exception_class
# except Exception as error:
# raise exception_class(getattr(self, 'error', None) or error)
def _validate_missing(self, value):
"""Validate missing values. Raise a :exc:`ValidationError` if
`value` should be considered missing.
"""
if value is missing:
if hasattr(self, 'required') and self.required:
default_message = 'Missing data for required field.'
message = (default_message if isinstance(self.required, bool) else
self.required)
raise ValidationError(message)
if value is None:
if hasattr(self, 'allow_none') and self.allow_none is not True:
default_message = 'Field may not be null.'
message = (default_message if isinstance(self.allow_none, bool) else
self.allow_none)
raise ValidationError(message)
def serialize(self, attr, obj, accessor=None):
"""Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param str attr: The attibute or key to get from the object.
:param str obj: The object to pull the key from.
:param callable accessor: Function used to pull values from ``obj``.
:raise MarshallingError: In case of formatting problem
"""
value = self.get_value(attr, obj, accessor=accessor)
if value is None and self._CHECK_ATTRIBUTE:
if hasattr(self, 'default') and self.default != null:
if callable(self.default):
return self.default()
else:
return self.default
func = lambda: self._serialize(value, attr, obj)
return self._call_and_reraise(func, MarshallingError)
def deserialize(self, value):
"""Deserialize ``value``.
:raise UnmarshallingError: If an invalid value is passed or if a required value
is missing.
"""
# Validate required fields, deserialize, then validate
# deserialized value
def do_deserialization():
self._validate_missing(value)
if getattr(self, 'allow_none', False) is True and value is None:
return None
output = self._deserialize(value)
self._validate(output)
return output
return self._call_and_reraise(do_deserialization, UnmarshallingError)
# Methods for concrete classes to override.
def _serialize(self, value, attr, obj):
"""Serializes ``value`` to a basic Python datatype. Noop by default.
Concrete :class:`Field` classes should implement this method.
Example: ::
class TitleCase(Field):
def _serialize(self, value, attr, obj):
if not value:
return ''
return unicode(value).title()
:param value: The value to be serialized.
:param str attr: The attribute or key on the object to be serialized.
:param object obj: The object the value was pulled from.
:raise MarshallingError: In case of formatting or validation failure.
"""
return value
def _deserialize(self, value):
"""Deserialize value. Concrete :class:`Field` classes should implement this method.
:raise UnmarshallingError: In case of formatting or validation failure.
"""
return value
@property
def context(self):
"""The context dictionary for the parent :class:`Schema`."""
return self.parent.context
class Raw(Field):
"""Field that applies no formatting or validation."""
pass
class Nested(Field):
"""Allows you to nest a :class:`Schema <marshmallow.Schema>`
inside a field.
Examples: ::
user = fields.Nested(UserSchema)
user2 = fields.Nested('UserSchema') # Equivalent to above
collaborators = fields.Nested(UserSchema, many=True, only='id')
parent = fields.Nested('self')
:param Schema nested: The Schema class or class name (string)
to nest, or ``"self"`` to nest the :class:`Schema` within itself.
:param default: Default value to if attribute is missing or None
:param tuple exclude: A list or tuple of fields to exclude.
:param only: A tuple or string of the field(s) to marshal. If `None`, all fields
will be marshalled. If a field name (string) is given, only a single
value will be returned as output instead of a dictionary.
This parameter takes precedence over ``exclude``.
:param bool allow_null: Whether to return None instead of a dictionary
with null keys, if a nested dictionary has all-null keys
:param bool many: Whether the field is a collection of objects.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
def __init__(self, nested, default=null, exclude=tuple(), only=None, allow_null=False,
many=False, **kwargs):
self.nested = nested
self.allow_null = allow_null
self.only = only
self.exclude = exclude
self.many = many
self.__schema = None # Cached Schema instance
self.__updated_fields = False
super(Nested, self).__init__(default=default, **kwargs)
@property
def schema(self):
"""The nested Schema object.
.. versionchanged:: 1.0.0
Renamed from `serializer` to `schema`
"""
# Ensure that only parameter is a tuple
if isinstance(self.only, basestring):
only = (self.only, )
else:
only = self.only
if not self.__schema:
if isinstance(self.nested, SchemaABC):
self.__schema = self.nested
elif isinstance(self.nested, type) and \
issubclass(self.nested, SchemaABC):
self.__schema = self.nested(many=self.many,
only=only, exclude=self.exclude)
elif isinstance(self.nested, basestring):
if self.nested == 'self':
parent_class = self.parent.__class__
self.__schema = parent_class(many=self.many, only=only,
exclude=self.exclude)
else:
schema_class = class_registry.get_class(self.nested)
self.__schema = schema_class(many=self.many,
only=only, exclude=self.exclude)
else:
raise ForcedError(ValueError('Nested fields must be passed a '
'Schema, not {0}.'
.format(self.nested.__class__)))
self.__schema.ordered = getattr(self.parent, 'ordered', False)
# Inherit context from parent
self.__schema.context.update(getattr(self.parent, 'context', {}))
return self.__schema
def _serialize(self, nested_obj, attr, obj):
if nested_obj is None:
if self.many:
return []
if self.allow_null:
return None
if not self.__updated_fields:
self.schema._update_fields(obj=nested_obj, many=self.many)
self.__updated_fields = True
try:
ret = self.schema.dump(nested_obj, many=self.many,
update_fields=not self.__updated_fields).data
except TypeError as err:
raise TypeError('Could not marshal nested object due to error:\n"{0}"\n'
'If the nested object is a collection, you need to set '
'"many=True".'.format(err))
if isinstance(self.only, basestring): # self.only is a field name
if self.many:
return utils.pluck(ret, key=self.only)
else:
return ret[self.only]
return ret
def _deserialize(self, value):
data, errors = self.schema.load(value)
if errors:
raise ValidationError(errors)
return data
class List(Field):
"""A list field, composed with another `Field` class or
instance.
Example: ::
numbers = fields.List(fields.Float)
:param Field cls_or_instance: A field class or instance.
:param bool default: Default value for serialization.
:param kwargs: The same keyword arguments that :class:`Field` receives.
.. versionchanged:: 2.0.0
The ``allow_none`` parameter now applies to deserialization and
has the same semantics as the other fields.
"""
# Values that are skipped by `Marshaller` if ``skip_missing=True``
SKIPPABLE_VALUES = (None, [], tuple())
def __init__(self, cls_or_instance, default=list, **kwargs):
super(List, self).__init__(**kwargs)
self.default = default
if isinstance(cls_or_instance, type):
if not issubclass(cls_or_instance, FieldABC):
raise ValueError('The type of the list elements '
'must be a subclass of '
'marshmallow.base.FieldABC')
self.container = cls_or_instance()
else:
if not isinstance(cls_or_instance, FieldABC):
raise ValueError('The instances of the list '
'elements must be of type '
'marshmallow.base.FieldABC')
self.container = cls_or_instance
def _serialize(self, value, attr, obj):
if utils.is_indexable_but_not_string(value) and not isinstance(value, dict):
return [self.container.serialize(idx, value) for idx
in range(len(value))]
if value is None:
return self.default
return [self.container.serialize(attr, obj)]
def _deserialize(self, value):
if utils.is_indexable_but_not_string(value) and not isinstance(value, dict):
# Convert all instances in typed list to container type
return [self.container.deserialize(each) for each in value]
if value is None:
return []
return [self.container.deserialize(value)]
class String(Field):
"""A string field.
:param allow_blank: Set to `True` if the empty string should be considered a
valid value. If not a `bool` (e.g. a `str`), the provided value will
be used as the message of the :exc:`ValidationError` instead
of the default message.
:param kwargs: The same keyword arguments that :class:`Field` receives.
.. versionchanged:: 2.0.0
Add `allow_blank` parameter. By default, the empty string will fail
validation.
"""
# Values that are skipped by `Marshaller` if ``skip_missing=True``
SKIPPABLE_VALUES = (None, '')
def __init__(self, default='', attribute=None, allow_blank=False, *args, **kwargs):
self.allow_blank = allow_blank
return super(String, self).__init__(default, attribute, *args, **kwargs)
def _validate_missing(self, value):
super(String, self)._validate_missing(value)
if value == '' and self.allow_blank is not True:
default_message = 'Field may not be blank.'
message = (default_message if isinstance(self.allow_blank, bool) else
self.allow_blank)
raise ValidationError(message)
def _serialize(self, value, attr, obj):
return utils.ensure_text_type(value)
def _deserialize(self, value):
result = utils.ensure_text_type(value)
return result
class UUID(String):
"""A UUID field."""
def _deserialize(self, value):
msg = 'Could not deserialize {0!r} to a UUID object.'.format(value)
err = UnmarshallingError(getattr(self, 'error', None) or msg)
try:
return uuid.UUID(value)
except (ValueError, AttributeError):
raise err
class Number(Field):
"""Base class for number fields.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
num_type = float
def __init__(self, default=0.0, attribute=None, as_string=False,
error=None, **kwargs):
self.as_string = as_string
super(Number, self).__init__(default=default, attribute=attribute,
error=error, **kwargs)
def _format_num(self, value):
"""Return the number value for value, given this field's `num_type`."""
return self.num_type(value)
def _validated(self, value, exception_class):
"""Format the value or raise ``exception_class`` if an error occurs."""
if value is None:
return self.default
try:
return self._format_num(value)
except (TypeError, ValueError, decimal.InvalidOperation) as err:
raise exception_class(getattr(self, 'error', None) or err)
def serialize(self, attr, obj, accessor=None):
"""Pulls the value for the given key from the object and returns the
serialized number representation. Return a string if `self.as_string=True`,
othewise return this field's `num_type`. Receives the same `args` and `kwargs`
as `Field`.
"""
ret = Field.serialize(self, attr, obj, accessor=accessor)
return str(ret) if self.as_string else ret
def _serialize(self, value, attr, obj):
return self._validated(value, MarshallingError)
def _deserialize(self, value):
return self._validated(value, UnmarshallingError)
class Integer(Number):
"""An integer field.
:param bool as_string: If True, format the value as a string.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
num_type = int
def __init__(self, default=0, attribute=None, as_string=False, error=None, **kwargs):
self.as_string = as_string
super(Integer, self).__init__(default=default, attribute=attribute,
error=error, **kwargs)
class Decimal(Number):
"""A field that (de)serializes to the Python ``decimal.Decimal`` type.
It's safe to use when dealing with money values, percentages, ratios
or other numbers where precision is critical.
.. warning::
This field serializes to a `decimal.Decimal` object by default. If you need
to render your data as JSON, keep in mind that the `json` module from the
standard library does not encode `decimal.Decimal`. Therefore, you must use
a JSON library that can handle decimals, such as `simplejson`, or serialize
to a string by passing ``as_string=True``.
:param int places: How many decimal places to quantize the value. If `None`, does
not quantize the value.
:param rounding: How to round the value during quantize, for example
`decimal.ROUND_UP`. If None, uses the rounding value from
the current thread's context.
:param default: The value this field defaults to. If not specified is the
`decimal.Decimal` zero.
:param bool as_string: If True, serialize to a string instead of a Python
`decimal.Decimal` type.
:param kwargs: The same keyword arguments that :class:`Number` receives.
.. versionadded:: 1.2.0
"""
num_type = decimal.Decimal
def __init__(self, places=None, rounding=None, default=decimal.Decimal(),
as_string=False, **kwargs):
self.places = decimal.Decimal((0, (1,), -places)) if places is not None else None
self.rounding = rounding
super(Decimal, self).__init__(default=default, as_string=as_string, **kwargs)
def _format_num(self, value):
num = decimal.Decimal(value)
if self.places is not None:
num = num.quantize(self.places, rounding=self.rounding)
return num
class Boolean(Field):
"""A boolean field.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
#: Values that will deserialize to `True`. If an empty set, any non-falsy
# value will deserialize to `True`.
truthy = set()
#: Values that will deserialize to `False`.
falsy = set(['False', 'false', '0', 'null', 'None'])
def _serialize(self, value, attr, obj):
return bool(value)
def _deserialize(self, value):
if not value:
return False
try:
value_str = text_type(value)
except TypeError as error:
raise UnmarshallingError(error)
if value_str in self.falsy:
return False
elif self.truthy:
if value_str in self.truthy:
return True
else:
raise UnmarshallingError(
'{0!r} is not in {1} nor {2}'.format(
value_str, self.truthy, self.falsy
))
return True
class FormattedString(Field):
"""Interpolate other values from the object into this field. The syntax for
the source string is the same as the string `str.format` method
from the python stdlib.
::
class UserSchema(Schema):
name = fields.String()
greeting = fields.FormattedString('Hello {name}')
ser = UserSchema()
res = ser.dump(user)
res.data # => {'name': 'Monty', 'greeting': 'Hello Monty'}
"""
# Values that are skipped by `Marshaller` if ``skip_missing=True``
SKIPPABLE_VALUES = (None, '')
def __init__(self, src_str, *args, **kwargs):
Field.__init__(self, *args, **kwargs)
self.src_str = text_type(src_str)
def _serialize(self, value, attr, obj):
try:
data = utils.to_marshallable_type(obj)
return self.src_str.format(**data)
except (TypeError, IndexError) as error:
raise MarshallingError(getattr(self, 'error', None) or error)
class Float(Number):
"""
A double as IEEE-754 double precision string.
:param bool as_string: If True, format the value as a string.
:param kwargs: The same keyword arguments that :class:`Number` receives.
"""
num_type = float
class Arbitrary(Number):
"""A floating point number with an arbitrary precision,
formatted as as string.
ex: 634271127864378216478362784632784678324.23432
:param kwargs: The same keyword arguments that :class:`Number` receives.
.. deprecated:: 1.2.0
Use `Decimal` instead.
"""
# No as_string param
def __init__(self, default='0', attribute=None, **kwargs):
warnings.warn(
'The Arbitrary field is deprecated. Use the Decimal field instead.',
category=DeprecationWarning
)
super(Arbitrary, self).__init__(default=default, attribute=attribute, **kwargs)
def _validated(self, value, exception_class):
"""Format ``value`` or raise ``exception_class`` if an error occurs."""
try:
if value is None:
return self.default
return text_type(utils.float_to_decimal(float(value)))
except ValueError as ve:
raise exception_class(ve)
def _serialize(self, value, attr, obj):
return self._validated(value, MarshallingError)
def _deserialize(self, value):
return self._validated(value, UnmarshallingError)
DATEFORMAT_SERIALIZATION_FUNCS = {
'iso': utils.isoformat,
'iso8601': utils.isoformat,
'rfc': utils.rfcformat,
'rfc822': utils.rfcformat,
}
DATEFORMAT_DESERIALIZATION_FUNCS = {
'iso': utils.from_iso,
'iso8601': utils.from_iso,
'rfc': utils.from_rfc,
'rfc822': utils.from_rfc,
}
class DateTime(Field):
"""A formatted datetime string in UTC.
Example: ``'2014-12-22T03:12:58.019077+00:00'``
:param str format: Either ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601),
or a date format string. If `None`, defaults to "iso".
:param default: Default value for the field if the attribute is not set.