-
-
Notifications
You must be signed in to change notification settings - Fork 621
/
fields.py
2111 lines (1732 loc) · 71.4 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
"""Field classes for various types of data."""
from __future__ import annotations
import collections
import copy
import datetime as dt
import numbers
import uuid
import ipaddress
import decimal
import math
import typing
import warnings
from enum import Enum as EnumType
from collections.abc import Mapping as _Mapping
from marshmallow import validate, utils, class_registry, types
from marshmallow.base import FieldABC, SchemaABC
from marshmallow.utils import (
is_collection,
missing as missing_,
resolve_field_instance,
is_aware,
)
from marshmallow.exceptions import (
ValidationError,
StringNotCollectionError,
FieldInstanceResolutionError,
)
from marshmallow.validate import And, Length
from marshmallow.warnings import RemovedInMarshmallow4Warning
__all__ = [
"Field",
"Raw",
"Nested",
"Mapping",
"Dict",
"List",
"Tuple",
"String",
"UUID",
"Number",
"Integer",
"Decimal",
"Boolean",
"Float",
"DateTime",
"NaiveDateTime",
"AwareDateTime",
"Time",
"Date",
"TimeDelta",
"Url",
"URL",
"Email",
"IP",
"IPv4",
"IPv6",
"IPInterface",
"IPv4Interface",
"IPv6Interface",
"Enum",
"Method",
"Function",
"Str",
"Bool",
"Int",
"Constant",
"Pluck",
]
_T = typing.TypeVar("_T")
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.
On error, the name of the field will be returned.
:param dump_default: If set, this value will be used during serialization if the
input value is missing. If not set, the field will be excluded from the
serialized output if the input value is missing. May be a value or a callable.
:param load_default: Default deserialization value for the field if the field is not
found in the input data. May be a value or a callable.
:param data_key: The name of the dict key in the external representation, i.e.
the input of `load` and the output of `dump`.
If `None`, the key will match the name of the field.
:param attribute: The name of the attribute to get the value from when serializing.
If `None`, assumes the attribute has the same name as the field.
Note: This should only be used for very specific use cases such as
outputting multiple fields for a single attribute. In most cases,
you should use ``data_key`` instead.
:param 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:`ValidationError` is raised.
:param required: Raise a :exc:`ValidationError` if the field value
is not supplied during deserialization.
:param allow_none: Set this to `True` if `None` should be considered a valid value during
validation/deserialization. If ``load_default=None`` and ``allow_none`` is unset,
will default to ``True``. Otherwise, the default is ``False``.
:param load_only: If `True` skip this field during serialization, otherwise
its value will be present in the serialized data.
:param 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 dict error_messages: Overrides for `Field.default_error_messages`.
:param metadata: Extra information to be stored as field metadata.
.. versionchanged:: 2.0.0
Removed `error` parameter. Use ``error_messages`` 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.
.. versionchanged:: 2.0.0
``default`` value is only used if explicitly set. Otherwise, missing values
inputs are excluded from serialized output.
.. versionchanged:: 3.0.0b8
Add ``data_key`` parameter for the specifying the key in the input and
output data. This parameter replaced both ``load_from`` and ``dump_to``.
"""
# Some fields, such as Method fields and Function fields, are not expected
# to exist as attributes on the objects to serialize. Set this to False
# for those fields
_CHECK_ATTRIBUTE = True
_creation_index = 0 # Used for sorting
#: Default error messages for various kinds of errors. The keys in this dictionary
#: are passed to `Field.make_error`. The values are error messages passed to
#: :exc:`marshmallow.exceptions.ValidationError`.
default_error_messages = {
"required": "Missing data for required field.",
"null": "Field may not be null.",
"validator_failed": "Invalid value.",
}
def __init__(
self,
*,
load_default: typing.Any = missing_,
missing: typing.Any = missing_,
dump_default: typing.Any = missing_,
default: typing.Any = missing_,
data_key: str | None = None,
attribute: str | None = None,
validate: (
None
| typing.Callable[[typing.Any], typing.Any]
| typing.Iterable[typing.Callable[[typing.Any], typing.Any]]
) = None,
required: bool = False,
allow_none: bool | None = None,
load_only: bool = False,
dump_only: bool = False,
error_messages: dict[str, str] | None = None,
metadata: typing.Mapping[str, typing.Any] | None = None,
**additional_metadata,
) -> None:
# handle deprecated `default` and `missing` parameters
if default is not missing_:
warnings.warn(
"The 'default' argument to fields is deprecated. "
"Use 'dump_default' instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
if dump_default is missing_:
dump_default = default
if missing is not missing_:
warnings.warn(
"The 'missing' argument to fields is deprecated. "
"Use 'load_default' instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
if load_default is missing_:
load_default = missing
self.dump_default = dump_default
self.load_default = load_default
self.attribute = attribute
self.data_key = data_key
self.validate = validate
if validate is None:
self.validators = []
elif callable(validate):
self.validators = [validate]
elif utils.is_iterable_but_not_string(validate):
self.validators = list(validate)
else:
raise ValueError(
"The 'validate' parameter must be a callable "
"or a collection of callables."
)
# If allow_none is None and load_default is None
# None should be considered valid by default
self.allow_none = load_default is None if allow_none is None else allow_none
self.load_only = load_only
self.dump_only = dump_only
if required is True and load_default is not missing_:
raise ValueError("'load_default' must not be set for required fields.")
self.required = required
metadata = metadata or {}
self.metadata = {**metadata, **additional_metadata}
if additional_metadata:
warnings.warn(
"Passing field metadata as keyword arguments is deprecated. Use the "
"explicit `metadata=...` argument instead. "
f"Additional metadata: {additional_metadata}",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
self._creation_index = Field._creation_index
Field._creation_index += 1
# Collect default error message from self and parent classes
messages = {} # type: dict[str, str]
for cls in reversed(self.__class__.__mro__):
messages.update(getattr(cls, "default_error_messages", {}))
messages.update(error_messages or {})
self.error_messages = messages
def __repr__(self) -> str:
return (
"<fields.{ClassName}(dump_default={self.dump_default!r}, "
"attribute={self.attribute!r}, "
"validate={self.validate}, required={self.required}, "
"load_only={self.load_only}, dump_only={self.dump_only}, "
"load_default={self.load_default}, allow_none={self.allow_none}, "
"error_messages={self.error_messages})>".format(
ClassName=self.__class__.__name__, self=self
)
)
def __deepcopy__(self, memo):
return copy.copy(self)
def get_value(self, obj, attr, accessor=None, default=missing_):
"""Return the value for a given key from an object.
:param object obj: The object to get the value from.
:param str attr: The attribute/key in `obj` to get the value from.
:param callable accessor: A callable used to retrieve the value of `attr` from
the object `obj`. Defaults to `marshmallow.utils.get_value`.
"""
accessor_func = accessor or utils.get_value
check_key = attr if self.attribute is None else self.attribute
return accessor_func(obj, check_key, default)
def _validate(self, value):
"""Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
does not succeed.
"""
self._validate_all(value)
@property
def _validate_all(self):
return And(*self.validators, error=self.error_messages["validator_failed"])
def make_error(self, key: str, **kwargs) -> ValidationError:
"""Helper method to make a `ValidationError` with an error message
from ``self.error_messages``.
"""
try:
msg = self.error_messages[key]
except KeyError as error:
class_name = self.__class__.__name__
message = (
"ValidationError raised by `{class_name}`, but error key `{key}` does "
"not exist in the `error_messages` dictionary."
).format(class_name=class_name, key=key)
raise AssertionError(message) from error
if isinstance(msg, (str, bytes)):
msg = msg.format(**kwargs)
return ValidationError(msg)
def fail(self, key: str, **kwargs):
"""Helper method that raises a `ValidationError` with an error message
from ``self.error_messages``.
.. deprecated:: 3.0.0
Use `make_error <marshmallow.fields.Field.make_error>` instead.
"""
warnings.warn(
'`Field.fail` is deprecated. Use `raise self.make_error("{}", ...)` instead.'.format(
key
),
RemovedInMarshmallow4Warning,
stacklevel=2,
)
raise self.make_error(key=key, **kwargs)
def _validate_missing(self, value):
"""Validate missing values. Raise a :exc:`ValidationError` if
`value` should be considered missing.
"""
if value is missing_ and self.required:
raise self.make_error("required")
if value is None and not self.allow_none:
raise self.make_error("null")
def serialize(
self,
attr: str,
obj: typing.Any,
accessor: typing.Callable[[typing.Any, str, typing.Any], typing.Any]
| None = None,
**kwargs,
):
"""Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param attr: The attribute/key to get from the object.
:param obj: The object to access the attribute/key from.
:param accessor: Function used to access values from ``obj``.
:param kwargs: Field-specific keyword arguments.
"""
if self._CHECK_ATTRIBUTE:
value = self.get_value(obj, attr, accessor=accessor)
if value is missing_:
default = self.dump_default
value = default() if callable(default) else default
if value is missing_:
return value
else:
value = None
return self._serialize(value, attr, obj, **kwargs)
def deserialize(
self,
value: typing.Any,
attr: str | None = None,
data: typing.Mapping[str, typing.Any] | None = None,
**kwargs,
):
"""Deserialize ``value``.
:param value: The value to deserialize.
:param attr: The attribute/key in `data` to deserialize.
:param data: The raw input data passed to `Schema.load`.
:param kwargs: Field-specific keyword arguments.
:raise ValidationError: If an invalid value is passed or if a required value
is missing.
"""
# Validate required fields, deserialize, then validate
# deserialized value
self._validate_missing(value)
if value is missing_:
_miss = self.load_default
return _miss() if callable(_miss) else _miss
if self.allow_none and value is None:
return None
output = self._deserialize(value, attr, data, **kwargs)
self._validate(output)
return output
# Methods for concrete classes to override.
def _bind_to_schema(self, field_name, schema):
"""Update field with values from its parent schema. Called by
:meth:`Schema._bind_field <marshmallow.Schema._bind_field>`.
:param str field_name: Field name set in schema.
:param Schema|Field schema: Parent object.
"""
self.parent = self.parent or schema
self.name = self.name or field_name
self.root = self.root or (
self.parent.root if isinstance(self.parent, FieldABC) else self.parent
)
def _serialize(
self, value: typing.Any, attr: str | None, obj: typing.Any, **kwargs
):
"""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, **kwargs):
if not value:
return ''
return str(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.
:param dict kwargs: Field-specific keyword arguments.
:return: The serialized value
"""
return value
def _deserialize(
self,
value: typing.Any,
attr: str | None,
data: typing.Mapping[str, typing.Any] | None,
**kwargs,
):
"""Deserialize value. Concrete :class:`Field` classes should implement this method.
:param value: The value to be deserialized.
:param attr: The attribute/key in `data` to be deserialized.
:param data: The raw input data passed to the `Schema.load`.
:param kwargs: Field-specific keyword arguments.
:raise ValidationError: In case of formatting or validation failure.
:return: The deserialized value.
.. versionchanged:: 2.0.0
Added ``attr`` and ``data`` parameters.
.. versionchanged:: 3.0.0
Added ``**kwargs`` to signature.
"""
return value
# Properties
@property
def context(self):
"""The context dictionary for the parent :class:`Schema`."""
return self.parent.context
# the default and missing properties are provided for compatibility and
# emit warnings when they are accessed and set
@property
def default(self):
warnings.warn(
"The 'default' attribute of fields is deprecated. "
"Use 'dump_default' instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
return self.dump_default
@default.setter
def default(self, value):
warnings.warn(
"The 'default' attribute of fields is deprecated. "
"Use 'dump_default' instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
self.dump_default = value
@property
def missing(self):
warnings.warn(
"The 'missing' attribute of fields is deprecated. "
"Use 'load_default' instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
return self.load_default
@missing.setter
def missing(self, value):
warnings.warn(
"The 'missing' attribute of fields is deprecated. "
"Use 'load_default' instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
self.load_default = value
class Raw(Field):
"""Field that applies no formatting."""
class Nested(Field):
"""Allows you to nest a :class:`Schema <marshmallow.Schema>`
inside a field.
Examples: ::
class ChildSchema(Schema):
id = fields.Str()
name = fields.Str()
# Use lambda functions when you need two-way nesting or self-nesting
parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True)
siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name"))))
class ParentSchema(Schema):
id = fields.Str()
children = fields.List(
fields.Nested(ChildSchema(only=("id", "parent", "siblings")))
)
spouse = fields.Nested(lambda: ParentSchema(only=("id",)))
When passing a `Schema <marshmallow.Schema>` instance as the first argument,
the instance's ``exclude``, ``only``, and ``many`` attributes will be respected.
Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`,
you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument.
::
# Yes
author = fields.Nested(UserSchema, only=('id', 'name'))
# No
author = fields.Nested(UserSchema(), only=('id', 'name'))
:param nested: `Schema` instance, class, class name (string), dictionary, or callable that
returns a `Schema` or dictionary. Dictionaries are converted with `Schema.from_dict`.
:param exclude: A list or tuple of fields to exclude.
:param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled.
This parameter takes precedence over ``exclude``.
:param many: Whether the field is a collection of objects.
:param unknown: Whether to exclude, include, or raise an error for unknown
fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
#: Default error messages.
default_error_messages = {"type": "Invalid type."}
def __init__(
self,
nested: SchemaABC
| type
| str
| dict[str, Field | type]
| typing.Callable[[], SchemaABC | dict[str, Field | type]],
*,
dump_default: typing.Any = missing_,
default: typing.Any = missing_,
only: types.StrSequenceOrSet | None = None,
exclude: types.StrSequenceOrSet = (),
many: bool = False,
unknown: str | None = None,
**kwargs,
):
# Raise error if only or exclude is passed as string, not list of strings
if only is not None and not is_collection(only):
raise StringNotCollectionError('"only" should be a collection of strings.')
if not is_collection(exclude):
raise StringNotCollectionError(
'"exclude" should be a collection of strings.'
)
if nested == "self":
warnings.warn(
"Passing 'self' to `Nested` is deprecated. "
"Use `Nested(lambda: MySchema(...))` instead.",
RemovedInMarshmallow4Warning,
stacklevel=2,
)
self.nested = nested
self.only = only
self.exclude = exclude
self.many = many
self.unknown = unknown
self._schema = None # Cached Schema instance
super().__init__(default=default, dump_default=dump_default, **kwargs)
@property
def schema(self):
"""The nested Schema object.
.. versionchanged:: 1.0.0
Renamed from `serializer` to `schema`.
"""
if not self._schema:
# Inherit context from parent.
context = getattr(self.parent, "context", {})
if callable(self.nested) and not isinstance(self.nested, type):
nested = self.nested()
else:
nested = self.nested
if isinstance(nested, dict):
# defer the import of `marshmallow.schema` to avoid circular imports
from marshmallow.schema import Schema
nested = Schema.from_dict(nested)
if isinstance(nested, SchemaABC):
self._schema = copy.copy(nested)
self._schema.context.update(context)
# Respect only and exclude passed from parent and re-initialize fields
set_class = self._schema.set_class
if self.only is not None:
if self._schema.only is not None:
original = self._schema.only
else: # only=None -> all fields
original = self._schema.fields.keys()
self._schema.only = set_class(self.only) & set_class(original)
if self.exclude:
original = self._schema.exclude
self._schema.exclude = set_class(self.exclude) | set_class(original)
self._schema._init_fields()
else:
if isinstance(nested, type) and issubclass(nested, SchemaABC):
schema_class = nested
elif not isinstance(nested, (str, bytes)):
raise ValueError(
"`Nested` fields must be passed a "
"`Schema`, not {}.".format(nested.__class__)
)
elif nested == "self":
schema_class = self.root.__class__
else:
schema_class = class_registry.get_class(nested)
self._schema = schema_class(
many=self.many,
only=self.only,
exclude=self.exclude,
context=context,
load_only=self._nested_normalized_option("load_only"),
dump_only=self._nested_normalized_option("dump_only"),
)
return self._schema
def _nested_normalized_option(self, option_name: str) -> list[str]:
nested_field = "%s." % self.name
return [
field.split(nested_field, 1)[1]
for field in getattr(self.root, option_name, set())
if field.startswith(nested_field)
]
def _serialize(self, nested_obj, attr, obj, **kwargs):
# Load up the schema first. This allows a RegistryError to be raised
# if an invalid schema name was passed
schema = self.schema
if nested_obj is None:
return None
many = schema.many or self.many
return schema.dump(nested_obj, many=many)
def _test_collection(self, value):
many = self.schema.many or self.many
if many and not utils.is_collection(value):
raise self.make_error("type", input=value, type=value.__class__.__name__)
def _load(self, value, data, partial=None):
try:
valid_data = self.schema.load(value, unknown=self.unknown, partial=partial)
except ValidationError as error:
raise ValidationError(
error.messages, valid_data=error.valid_data
) from error
return valid_data
def _deserialize(self, value, attr, data, partial=None, **kwargs):
"""Same as :meth:`Field._deserialize` with additional ``partial`` argument.
:param bool|tuple partial: For nested schemas, the ``partial``
parameter passed to `Schema.load`.
.. versionchanged:: 3.0.0
Add ``partial`` parameter.
"""
self._test_collection(value)
return self._load(value, data, partial=partial)
class Pluck(Nested):
"""Allows you to replace nested data with one of the data's fields.
Example: ::
from marshmallow import Schema, fields
class ArtistSchema(Schema):
id = fields.Int()
name = fields.Str()
class AlbumSchema(Schema):
artist = fields.Pluck(ArtistSchema, 'id')
in_data = {'artist': 42}
loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}}
dumped = AlbumSchema().dump(loaded) # => {'artist': 42}
:param Schema nested: The Schema class or class name (string)
to nest, or ``"self"`` to nest the :class:`Schema` within itself.
:param str field_name: The key to pluck a value from.
:param kwargs: The same keyword arguments that :class:`Nested` receives.
"""
def __init__(
self,
nested: SchemaABC | type | str | typing.Callable[[], SchemaABC],
field_name: str,
**kwargs,
):
super().__init__(nested, only=(field_name,), **kwargs)
self.field_name = field_name
@property
def _field_data_key(self):
only_field = self.schema.fields[self.field_name]
return only_field.data_key or self.field_name
def _serialize(self, nested_obj, attr, obj, **kwargs):
ret = super()._serialize(nested_obj, attr, obj, **kwargs)
if ret is None:
return None
if self.many:
return utils.pluck(ret, key=self._field_data_key)
return ret[self._field_data_key]
def _deserialize(self, value, attr, data, partial=None, **kwargs):
self._test_collection(value)
if self.many:
value = [{self._field_data_key: v} for v in value]
else:
value = {self._field_data_key: value}
return self._load(value, data, partial=partial)
class List(Field):
"""A list field, composed with another `Field` class or
instance.
Example: ::
numbers = fields.List(fields.Float())
:param cls_or_instance: A field class or instance.
: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.
.. versionchanged:: 3.0.0rc9
Does not serialize scalar values to single-item lists.
"""
#: Default error messages.
default_error_messages = {"invalid": "Not a valid list."}
def __init__(self, cls_or_instance: Field | type, **kwargs):
super().__init__(**kwargs)
try:
self.inner = resolve_field_instance(cls_or_instance)
except FieldInstanceResolutionError as error:
raise ValueError(
"The list elements must be a subclass or instance of "
"marshmallow.base.FieldABC."
) from error
if isinstance(self.inner, Nested):
self.only = self.inner.only
self.exclude = self.inner.exclude
def _bind_to_schema(self, field_name, schema):
super()._bind_to_schema(field_name, schema)
self.inner = copy.deepcopy(self.inner)
self.inner._bind_to_schema(field_name, self)
if isinstance(self.inner, Nested):
self.inner.only = self.only
self.inner.exclude = self.exclude
def _serialize(self, value, attr, obj, **kwargs) -> list[typing.Any] | None:
if value is None:
return None
return [self.inner._serialize(each, attr, obj, **kwargs) for each in value]
def _deserialize(self, value, attr, data, **kwargs) -> list[typing.Any]:
if not utils.is_collection(value):
raise self.make_error("invalid")
result = []
errors = {}
for idx, each in enumerate(value):
try:
result.append(self.inner.deserialize(each, **kwargs))
except ValidationError as error:
if error.valid_data is not None:
result.append(error.valid_data)
errors.update({idx: error.messages})
if errors:
raise ValidationError(errors, valid_data=result)
return result
class Tuple(Field):
"""A tuple field, composed of a fixed number of other `Field` classes or
instances
Example: ::
row = Tuple((fields.String(), fields.Integer(), fields.Float()))
.. note::
Because of the structured nature of `collections.namedtuple` and
`typing.NamedTuple`, using a Schema within a Nested field for them is
more appropriate than using a `Tuple` field.
:param Iterable[Field] tuple_fields: An iterable of field classes or
instances.
:param kwargs: The same keyword arguments that :class:`Field` receives.
.. versionadded:: 3.0.0rc4
"""
#: Default error messages.
default_error_messages = {"invalid": "Not a valid tuple."}
def __init__(self, tuple_fields, *args, **kwargs):
super().__init__(*args, **kwargs)
if not utils.is_collection(tuple_fields):
raise ValueError(
"tuple_fields must be an iterable of Field classes or " "instances."
)
try:
self.tuple_fields = [
resolve_field_instance(cls_or_instance)
for cls_or_instance in tuple_fields
]
except FieldInstanceResolutionError as error:
raise ValueError(
'Elements of "tuple_fields" must be subclasses or '
"instances of marshmallow.base.FieldABC."
) from error
self.validate_length = Length(equal=len(self.tuple_fields))
def _bind_to_schema(self, field_name, schema):
super()._bind_to_schema(field_name, schema)
new_tuple_fields = []
for field in self.tuple_fields:
field = copy.deepcopy(field)
field._bind_to_schema(field_name, self)
new_tuple_fields.append(field)
self.tuple_fields = new_tuple_fields
def _serialize(self, value, attr, obj, **kwargs) -> tuple | None:
if value is None:
return None
return tuple(
field._serialize(each, attr, obj, **kwargs)
for field, each in zip(self.tuple_fields, value)
)
def _deserialize(self, value, attr, data, **kwargs) -> tuple:
if not utils.is_collection(value):
raise self.make_error("invalid")
self.validate_length(value)
result = []
errors = {}
for idx, (field, each) in enumerate(zip(self.tuple_fields, value)):
try:
result.append(field.deserialize(each, **kwargs))
except ValidationError as error:
if error.valid_data is not None:
result.append(error.valid_data)
errors.update({idx: error.messages})
if errors:
raise ValidationError(errors, valid_data=result)
return tuple(result)
class String(Field):
"""A string field.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
#: Default error messages.
default_error_messages = {
"invalid": "Not a valid string.",
"invalid_utf8": "Not a valid utf-8 string.",
}
def _serialize(self, value, attr, obj, **kwargs) -> str | None:
if value is None:
return None
return utils.ensure_text_type(value)
def _deserialize(self, value, attr, data, **kwargs) -> typing.Any:
if not isinstance(value, (str, bytes)):
raise self.make_error("invalid")
try:
return utils.ensure_text_type(value)
except UnicodeDecodeError as error:
raise self.make_error("invalid_utf8") from error
class UUID(String):
"""A UUID field."""
#: Default error messages.
default_error_messages = {"invalid_uuid": "Not a valid UUID."}
def _validated(self, value) -> uuid.UUID | None:
"""Format the value or raise a :exc:`ValidationError` if an error occurs."""
if value is None:
return None
if isinstance(value, uuid.UUID):
return value
try:
if isinstance(value, bytes) and len(value) == 16:
return uuid.UUID(bytes=value)
return uuid.UUID(value)
except (ValueError, AttributeError, TypeError) as error:
raise self.make_error("invalid_uuid") from error
def _deserialize(self, value, attr, data, **kwargs) -> uuid.UUID | None:
return self._validated(value)
class Number(Field):
"""Base class for number fields.
:param bool as_string: If `True`, format the serialized value as a string.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
num_type = float # type: typing.Type
#: Default error messages.
default_error_messages = {
"invalid": "Not a valid number.",
"too_large": "Number too large.",
}
def __init__(self, *, as_string: bool = False, **kwargs):
self.as_string = as_string
super().__init__(**kwargs)
def _format_num(self, value) -> typing.Any:
"""Return the number value for value, given this field's `num_type`."""
return self.num_type(value)
def _validated(self, value) -> _T | None:
"""Format the value or raise a :exc:`ValidationError` if an error occurs."""
if value is None:
return None
# (value is True or value is False) is ~5x faster than isinstance(value, bool)
if value is True or value is False:
raise self.make_error("invalid", input=value)
try:
return self._format_num(value)
except (TypeError, ValueError) as error:
raise self.make_error("invalid", input=value) from error
except OverflowError as error:
raise self.make_error("too_large", input=value) from error
def _to_string(self, value) -> str:
return str(value)
def _serialize(self, value, attr, obj, **kwargs) -> str | _T | None:
"""Return a string if `self.as_string=True`, otherwise return this field's `num_type`."""
if value is None:
return None
ret = self._format_num(value) # type: _T
return self._to_string(ret) if self.as_string else ret
def _deserialize(self, value, attr, data, **kwargs) -> _T | None:
return self._validated(value)
class Integer(Number):
"""An integer field.
:param strict: If `True`, only integer types are valid.
Otherwise, any value castable to `int` is valid.
:param kwargs: The same keyword arguments that :class:`Number` receives.
"""
num_type = int
#: Default error messages.
default_error_messages = {"invalid": "Not a valid integer."}
def __init__(self, *, strict: bool = False, **kwargs):
self.strict = strict
super().__init__(**kwargs)
# override Number
def _validated(self, value):