API Reference¶
Schema¶
-
class
marshmallow.Schema(extra=None, only=None, exclude=(), prefix='', strict=None, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]¶ Base schema class with which to define custom schemas.
Example usage:
import datetime as dt from marshmallow import Schema, fields class Album(object): def __init__(self, title, release_date): self.title = title self.release_date = release_date class AlbumSchema(Schema): title = fields.Str() release_date = fields.Date() # Or, equivalently class AlbumSchema2(Schema): class Meta: fields = ("title", "release_date") album = Album("Beggars Banquet", dt.date(1968, 12, 6)) schema = AlbumSchema() data, errors = schema.dump(album) data # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}
Parameters: - extra (dict) – A dict of extra attributes to bind to the serialized result.
- only (tuple|list) – Whitelist of fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters.
- exclude (tuple|list) – Blacklist of fields to exclude when instantiating the Schema.
If a field appears in both
onlyandexclude, it is not used. Nested fields can be represented with dot delimiters. - prefix (str) – Optional prefix that will be prepended to all the serialized field names.
- strict (bool) – If
True, raise errors if invalid data are passed in instead of failing silently and storing the errors. - many (bool) – Should be set to
Trueifobjis a collection so that the object will be serialized to a list. - context (dict) – Optional context passed to
fields.Methodandfields.Functionfields. - load_only (tuple|list) – Fields to skip during serialization (write-only fields)
- dump_only (tuple|list) – Fields to skip during deserialization (read-only fields)
- partial (bool|tuple) – Whether to ignore missing fields. If its value is an iterable, only missing fields listed in that iterable will be ignored.
Changed in version 2.0.0:
__validators__,__preprocessors__, and__data_handlers__are removed in favor ofmarshmallow.decorators.validates_schema,marshmallow.decorators.pre_loadandmarshmallow.decorators.post_dump.__accessor__and__error_handler__are deprecated. Implement thehandle_errorandget_attributemethods instead.-
class
Meta¶ Options object for a Schema.
Example usage:
class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute")
Available options:
fields: Tuple or list of fields to include in the serialized result.additional: Tuple or list of fields to include in addition to the- explicitly declared fields.
additionalandfieldsare mutually-exclusive options.
include: Dictionary of additional fields to include in the schema. It is- usually better to define fields as class variables, but you may need to
use this option, e.g., if your fields are Python keywords. May be an
OrderedDict.
exclude: Tuple or list of fields to exclude in the serialized result.- Nested fields can be represented with dot delimiters.
dateformat: Date format for all DateTime fields that do not have their- date format explicitly specified.
strict: IfTrue, raise errors during marshalling rather than- storing them.
json_module: JSON module to use forloadsanddumps.- Defaults to the
jsonmodule in the stdlib.
ordered: IfTrue, order serialization output according to the- order in which fields were declared. Output of
Schema.dumpwill be acollections.OrderedDict.
index_errors: IfTrue, errors dictionaries will include the index- of invalid items in a collection.
load_only: Tuple or list of fields to exclude from serialized results.dump_only: Tuple or list of fields to exclude from deserialization
-
OPTIONS_CLASS¶ alias of
SchemaOpts
-
classmethod
accessor(func)¶ Decorator that registers a function for pulling values from an object to serialize. The function receives the
Schemainstance, thekeyof the value to get, theobjto serialize, and an optionaldefaultvalue.Deprecated since version 2.0.0: Set the
error_handlerclass Meta option instead.
-
dump(obj, many=None, update_fields=True, **kwargs)¶ Serialize an object to native Python data types according to this Schema’s fields.
Parameters: - obj – The object to serialize.
- many (bool) – Whether to serialize
objas a collection. IfNone, the value forself.manyis used. - update_fields (bool) – Whether to update the schema’s field classes. Typically
set to
True, but may beFalsewhen serializing a homogenous collection. This parameter is used byfields.Nestedto avoid multiple updates.
Returns: A tuple of the form (
data,errors)Return type: MarshalResult, acollections.namedtupleNew in version 1.0.0.
-
dumps(obj, many=None, update_fields=True, *args, **kwargs)¶ Same as
dump(), except return a JSON-encoded string.Parameters: - obj – The object to serialize.
- many (bool) – Whether to serialize
objas a collection. IfNone, the value forself.manyis used. - update_fields (bool) – Whether to update the schema’s field classes. Typically
set to
True, but may beFalsewhen serializing a homogenous collection. This parameter is used byfields.Nestedto avoid multiple updates.
Returns: A tuple of the form (
data,errors)Return type: MarshalResult, acollections.namedtupleNew in version 1.0.0.
-
classmethod
error_handler(func)¶ Decorator that registers an error handler function for the schema. The function receives the
Schemainstance, a dictionary of errors, and the serialized object (if serializing data) or data dictionary (if deserializing data) as arguments.Example:
class UserSchema(Schema): email = fields.Email() @UserSchema.error_handler def handle_errors(schema, errors, obj): raise ValueError('An error occurred while marshalling {}'.format(obj)) user = User(email='invalid') UserSchema().dump(user) # => raises ValueError UserSchema().load({'email': 'bademail'}) # raises ValueError
New in version 0.7.0.
Deprecated since version 2.0.0: Set the
error_handlerclass Meta option instead.
-
get_attribute(attr, obj, default)¶ Defines how to pull values from an object to serialize.
New in version 2.0.0.
-
handle_error(error, data)¶ Custom error handler function for the schema.
Parameters: - error (ValidationError) – The
ValidationErrorraised during (de)serialization. - data – The original input data.
New in version 2.0.0.
- error (ValidationError) – The
-
load(data, many=None, partial=None)¶ Deserialize a data structure to an object defined by this Schema’s fields and
make_object().Parameters: - data (dict) – The data to deserialize.
- many (bool) – Whether to deserialize
dataas a collection. IfNone, the value forself.manyis used. - partial (bool|tuple) – Whether to ignore missing fields. If
None, the value forself.partialis used. If its value is an iterable, only missing fields listed in that iterable will be ignored.
Returns: A tuple of the form (
data,errors)Return type: UnmarshalResult, acollections.namedtupleNew in version 1.0.0.
-
loads(json_data, many=None, *args, **kwargs)¶ Same as
load(), except it takes a JSON string as input.Parameters: - json_data (str) – A JSON string of the data to deserialize.
- many (bool) – Whether to deserialize
objas a collection. IfNone, the value forself.manyis used. - partial (bool|tuple) – Whether to ignore missing fields. If
None, the value forself.partialis used. If its value is an iterable, only missing fields listed in that iterable will be ignored.
Returns: A tuple of the form (
data,errors)Return type: UnmarshalResult, acollections.namedtupleNew in version 1.0.0.
-
on_bind_field(field_name, field_obj)¶ Hook to modify a field when it is bound to the
Schema. No-op by default.
-
validate(data, many=None, partial=None)¶ Validate
dataagainst the schema, returning a dictionary of validation errors.Parameters: - data (dict) – The data to validate.
- many (bool) – Whether to validate
dataas a collection. IfNone, the value forself.manyis used. - partial (bool|tuple) – Whether to ignore missing fields. If
None, the value forself.partialis used. If its value is an iterable, only missing fields listed in that iterable will be ignored.
Returns: A dictionary of validation errors.
Return type: dict
New in version 1.1.0.
-
class
marshmallow.MarshalResult(data, errors)¶ Return type of
Schema.dump()including serialized data and errors
-
class
marshmallow.UnmarshalResult(data, errors)¶ Return type of
Schema.load(), including deserialized data and errors
-
marshmallow.pprint(obj, *args, **kwargs)[source]¶ Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of
marshmallow.Schema.dump().
Fields¶
Field classes for various types of data.
-
class
marshmallow.fields.Field(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ 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.
Parameters: - 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.
- attribute (str) – The name of the attribute to get the value from. If
None, assumes the attribute has the same name as the field. - load_from (str) – Additional key to look for when deserializing. Will only be checked if the field’s name is not found on the input dictionary. If checked, it will return this parameter on error.
- dump_to (str) – Field name to use as a key when serializing.
- validate (callable) – 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, anValidationErroris raised. - required – Raise a
ValidationErrorif the field value is not supplied during deserialization. - allow_none – Set this to
TrueifNoneshould be considered a valid value during validation/deserialization. Ifmissing=Noneandallow_noneis unset, will default toTrue. Otherwise, the default isFalse. - load_only (bool) – If
Trueskip this field during serialization, otherwise its value will be present in the serialized data. - dump_only (bool) – If
Trueskip 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”. - missing – Default deserialization value for the field if the field is not found in the input data. May be a value or a callable.
- error_messages (dict) – Overrides for
Field.default_error_messages. - metadata – Extra arguments to be stored as metadata.
Changed in version 2.0.0: Removed
errorparameter. Useerror_messagesinstead.Changed in version 2.0.0: Added
allow_noneparameter, which makes validation/deserialization ofNoneconsistent across fields.Changed in version 2.0.0: Added
load_onlyanddump_onlyparameters, which allow field skipping during the (de)serialization process.Changed in version 2.0.0: Added
missingparameter, which indicates the value for a field if the field is not found during deserialization.Changed in version 2.0.0:
defaultvalue is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output.-
_add_to_schema(field_name, schema)[source]¶ - Update field with values from its parent schema. Called by
__set_field_attrs.
Parameters: - field_name (str) – Field name set in schema.
- schema (Schema) – Parent schema.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
_validate(value)[source]¶ Perform validation on
value. Raise aValidationErrorif validation does not succeed.
-
_validate_missing(value)[source]¶ Validate missing values. Raise a
ValidationErrorifvalueshould be considered missing.
-
context¶ The context dictionary for the parent
Schema.
-
default_error_messages= {'null': 'Field may not be null.', 'required': 'Missing data for required field.', 'type': 'Invalid input type.', 'validator_failed': 'Invalid value.'}¶ Default error messages for various kinds of errors. The keys in this dictionary are passed to
Field.fail. The values are error messages passed tomarshmallow.ValidationError.
-
deserialize(value, attr=None, data=None)[source]¶ Deserialize
value.Raises: ValidationError – If an invalid value is passed or if a required value is missing.
-
get_value(attr, obj, accessor=None, default=<marshmallow.missing>)[source]¶ Return the value for a given key from an object.
-
root¶ Reference to the
Schemathat this field belongs to even if it is buried in aList. ReturnNonefor unbound fields.
-
serialize(attr, obj, accessor=None)[source]¶ Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
Parameters: - attr (str) – The attibute or key to get from the object.
- obj (str) – The object to pull the key from.
- accessor (callable) – Function used to pull values from
obj.
Raises: ValidationError – In case of formatting problem
-
class
marshmallow.fields.Raw(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ Field that applies no formatting or validation.
-
class
marshmallow.fields.Nested(nested, default=<marshmallow.missing>, exclude=(), only=None, **kwargs)[source]¶ Allows you to nest a
Schemainside 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')
When passing a
Schemainstance as the first argument, the instance’sexclude,only, andmanyattributes will be respected.Therefore, when passing the
exclude,only, ormanyarguments tofields.Nested, you should pass aSchemaclass (not an instance) as the first argument.# Yes author = fields.Nested(UserSchema, only=('id', 'name')) # No author = fields.Nested(UserSchema(), only=('id', 'name'))
Parameters: - nested (Schema) – The Schema class or class name (string)
to nest, or
"self"to nest theSchemawithin itself. - exclude (tuple) – A list or tuple of fields to exclude.
- required – Raise an
ValidationErrorduring deserialization if the field, and any required field values specified in thenestedschema, are not found in the data. If not abool(e.g. astr), the provided value will be used as the message of theValidationErrorinstead of the default message. - 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 overexclude. - many (bool) – Whether the field is a collection of objects.
- kwargs – The same keyword arguments that
Fieldreceives.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(nested_obj, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
- nested (Schema) – The Schema class or class name (string)
to nest, or
-
class
marshmallow.fields.Dict(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ A dict field. Supports dicts and dict-like objects.
Note
This field is only appropriate when the structure of nested data is not known. For structured data, use
Nested.New in version 2.1.0.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
-
class
marshmallow.fields.List(cls_or_instance, **kwargs)[source]¶ A list field, composed with another
Fieldclass or instance.Example:
numbers = fields.List(fields.Float())
Parameters: Changed in version 2.0.0: The
allow_noneparameter now applies to deserialization and has the same semantics as the other fields.-
_add_to_schema(field_name, schema)[source]¶ - Update field with values from its parent schema. Called by
__set_field_attrs.
Parameters: - field_name (str) – Field name set in schema.
- schema (Schema) – Parent schema.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
-
class
marshmallow.fields.String(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ A string field.
Parameters: kwargs – The same keyword arguments that Fieldreceives.-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
-
class
marshmallow.fields.UUID(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ A UUID field.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
-
class
marshmallow.fields.Number(as_string=False, **kwargs)[source]¶ Base class for number fields.
Parameters: - as_string (bool) – If True, format the serialized value as a string.
- kwargs – The same keyword arguments that
Fieldreceives.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Return a string if
self.as_string=True, otherwise return this field’snum_type.
-
num_type¶ alias of
builtins.float
-
class
marshmallow.fields.Integer(as_string=False, **kwargs)[source]¶ An integer field.
Parameters: kwargs – The same keyword arguments that Numberreceives.-
num_type¶ alias of
builtins.int
-
-
class
marshmallow.fields.Decimal(places=None, rounding=None, allow_nan=False, as_string=False, **kwargs)[source]¶ A field that (de)serializes to the Python
decimal.Decimaltype. 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.Decimalobject by default. If you need to render your data as JSON, keep in mind that thejsonmodule from the standard library does not encodedecimal.Decimal. Therefore, you must use a JSON library that can handle decimals, such assimplejson, or serialize to a string by passingas_string=True.Warning
If a JSON
floatvalue is passed to this field for deserialization it will first be cast to its correspondingstringvalue before being deserialized to adecimal.Decimalobject. The default__str__implementation of the built-in Pythonfloattype may apply a destructive transformation upon its input data and therefore cannot be relied upon to preserve precision. To avoid this, you can instead pass a JSONstringto be deserialized directly.Parameters: - places (int) – How many decimal places to quantize the value. If
None, does not quantize the value. - 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. - allow_nan (bool) – If
True,NaN,Infinityand-Infinityare allowed, even though they are illegal according to the JSON specification. - as_string (bool) – If True, serialize to a string instead of a Python
decimal.Decimaltype. - kwargs – The same keyword arguments that
Numberreceives.
New in version 1.2.0.
-
num_type¶ alias of
decimal.Decimal
- places (int) – How many decimal places to quantize the value. If
-
class
marshmallow.fields.Boolean(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ A boolean field.
Parameters: kwargs – The same keyword arguments that Fieldreceives.-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
falsy= {0, 'f', 'false', 'FALSE', 'F', '0', 'False'}¶ Values that will (de)serialize to
False.
-
-
class
marshmallow.fields.FormattedString(src_str, *args, **kwargs)[source]¶ Interpolate other values from the object into this field. The syntax for the source string is the same as the string
str.formatmethod 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'}
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
-
class
marshmallow.fields.Float(as_string=False, **kwargs)[source]¶ A double as IEEE-754 double precision string.
Parameters: - as_string (bool) – If True, format the value as a string.
- kwargs – The same keyword arguments that
Numberreceives.
-
num_type¶ alias of
builtins.float
-
class
marshmallow.fields.DateTime(format=None, **kwargs)[source]¶ A formatted datetime string in UTC.
Example:
'2014-12-22T03:12:58.019077+00:00'Timezone-naive
datetimeobjects are converted to UTC (+00:00) bySchema.dump.Schema.loadreturnsdatetimeobjects that are timezone-aware.Parameters: - format (str) – Either
"rfc"(for RFC822),"iso"(for ISO8601), or a date format string. IfNone, defaults to “iso”. - kwargs – The same keyword arguments that
Fieldreceives.
-
_add_to_schema(field_name, schema)[source]¶ - Update field with values from its parent schema. Called by
__set_field_attrs.
Parameters: - field_name (str) – Field name set in schema.
- schema (Schema) – Parent schema.
-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
- format (str) – Either
-
class
marshmallow.fields.LocalDateTime(format=None, **kwargs)[source]¶ A formatted datetime string in localized time, relative to UTC.
ex."Sun, 10 Nov 2013 08:23:45 -0600"Takes the same arguments as
DateTime.
-
class
marshmallow.fields.Time(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ ISO8601-formatted time string.
Parameters: kwargs – The same keyword arguments that Fieldreceives.-
_deserialize(value, attr, data)[source]¶ Deserialize an ISO8601-formatted time to a
datetime.timeobject.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
-
class
marshmallow.fields.Date(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ ISO8601-formatted date string.
Parameters: kwargs – The same keyword arguments that Fieldreceives.-
_deserialize(value, attr, data)[source]¶ Deserialize an ISO8601-formatted date string to a
datetime.dateobject.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
-
class
marshmallow.fields.TimeDelta(precision='seconds', error=None, **kwargs)[source]¶ A field that (de)serializes a
datetime.timedeltaobject to an integer and vice versa. The integer can represent the number of days, seconds or microseconds.Parameters: - precision (str) – Influences how the integer is interpreted during (de)serialization. Must be ‘days’, ‘seconds’ or ‘microseconds’.
- error (str) – Error message stored upon validation failure.
- kwargs – The same keyword arguments that
Fieldreceives.
Changed in version 2.0.0: Always serializes to an integer value to avoid rounding errors. Add
precisionparameter.-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
class
marshmallow.fields.Url(relative=False, schemes=None, **kwargs)[source]¶ A validated URL field. Validation occurs during both serialization and deserialization.
Parameters: - default – Default value for the field if the attribute is not set.
- attribute (str) – The name of the attribute to get the value from. If
None, assumes the attribute has the same name as the field. - relative (bool) – Allow relative URLs.
- kwargs – The same keyword arguments that
Stringreceives.
-
marshmallow.fields.URL¶ alias of
marshmallow.fields.Url
-
class
marshmallow.fields.Email(*args, **kwargs)[source]¶ A validated email field. Validation occurs during both serialization and deserialization.
Parameters:
-
class
marshmallow.fields.Method(serialize=None, deserialize=None, method_name=None, **kwargs)[source]¶ A field that takes the value returned by a
Schemamethod.Parameters: - method_name (str) – The name of the Schema method from which
to retrieve the value. The method must take an argument
obj(in addition to self) that is the object to be serialized. - deserialize (str) – Optional name of the Schema method for deserializing
a value The method must take a single argument
value, which is the value to deserialize.
Changed in version 2.0.0: Removed optional
contextparameter on methods. Useself.contextinstead.Changed in version 2.3.0: Deprecated
method_nameparameter in favor ofserializeand allowserializeto not be passed at all.-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
- method_name (str) – The name of the Schema method from which
to retrieve the value. The method must take an argument
-
class
marshmallow.fields.Function(serialize=None, deserialize=None, func=None, **kwargs)[source]¶ A field that takes the value returned by a function.
Parameters: - serialize (callable) – A callable from which to retrieve the value.
The function must take a single argument
objwhich is the object to be serialized. It can also optionally take acontextargument, which is a dictionary of context variables passed to the serializer. If no callable is provided then the`load_only`flag will be set to True. - deserialize (callable) – A callable from which to retrieve the value.
The function must take a single argument
valuewhich is the value to be deserialized. It can also optionally take acontextargument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then`value`will be passed through unchanged. - func (callable) – This argument is to be deprecated. It exists for backwards compatiblity. Use serialize instead.
Changed in version 2.3.0: Deprecated
funcparameter in favor ofserialize.-
_deserialize(value, attr, data)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, attr, obj)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
- serialize (callable) – A callable from which to retrieve the value.
The function must take a single argument
-
marshmallow.fields.Str¶ alias of
marshmallow.fields.String
-
marshmallow.fields.Bool¶ alias of
marshmallow.fields.Boolean
-
marshmallow.fields.Int¶ alias of
marshmallow.fields.Integer
-
class
marshmallow.fields.Constant(constant, **kwargs)[source]¶ A field that (de)serializes to a preset constant. If you only want the constant added for serialization or deserialization, you should use
dump_only=Trueorload_only=Truerespectively.Parameters: constant – The constant to return for the field attribute. New in version 2.0.0.
-
_deserialize(value, *args, **kwargs)[source]¶ Deserialize value. Concrete
Fieldclasses should implement this method.Parameters: - value – The value to be deserialized.
- attr (str) – The attribute/key in
datato be deserialized. - data (dict) – The raw input data passed to the
Schema.load.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The deserialized value.
Changed in version 2.0.0: Added
attranddataparameters.
-
_serialize(value, *args, **kwargs)[source]¶ Serializes
valueto a basic Python datatype. Noop by default. ConcreteFieldclasses should implement this method.Example:
class TitleCase(Field): def _serialize(self, value, attr, obj): if not value: return '' return unicode(value).title()
Parameters: - value – The value to be serialized.
- attr (str) – The attribute or key on the object to be serialized.
- obj (object) – The object the value was pulled from.
Raises: ValidationError – In case of formatting or validation failure.
Returns: The serialized value
-
Decorators¶
Decorators for registering schema pre-processing and post-processing methods.
These should be imported from the top-level marshmallow module.
Example:
from marshmallow import (
Schema, pre_load, pre_dump, post_load, validates_schema,
validates, fields, ValidationError
)
class UserSchema(Schema):
email = fields.Str(required=True)
age = fields.Integer(required=True)
@post_load
def lowerstrip_email(self, item):
item['email'] = item['email'].lower().strip()
return item
@pre_load(pass_many=True)
def remove_envelope(self, data, many):
namespace = 'results' if many else 'result'
return data[namespace]
@post_dump(pass_many=True)
def add_envelope(self, data, many):
namespace = 'results' if many else 'result'
return {namespace: data}
@validates_schema
def validate_email(self, data):
if len(data['email']) < 3:
raise ValidationError('Email must be more than 3 characters', 'email')
@validates('age')
def validate_age(self, data):
if data < 14:
raise ValidationError('Too young!')
Note
These decorators only work with instance methods. Class and static methods are not supported.
Warning
The invocation order of decorated methods of the same type is not guaranteed. If you need to guarantee order of different processing steps, you should put them in the same processing method.
-
marshmallow.decorators.post_dump(fn=None, pass_many=False, pass_original=False)[source]¶ Register a method to invoke after serializing an object. The method receives the serialized object and returns the processed object.
By default, receives a single object at a time, transparently handling the
manyargument passed to the Schema. Ifpass_many=True, the raw data (which may be a collection) and the value formanyis passed.
-
marshmallow.decorators.post_load(fn=None, pass_many=False, pass_original=False)[source]¶ Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data.
By default, receives a single datum at a time, transparently handling the
manyargument passed to the Schema. Ifpass_many=True, the raw data (which may be a collection) and the value formanyis passed.
-
marshmallow.decorators.pre_dump(fn=None, pass_many=False)[source]¶ Register a method to invoke before serializing an object. The method receives the object to be serialized and returns the processed object.
By default, receives a single object at a time, regardless of whether
many=Trueis passed to theSchema. Ifpass_many=True, the raw data (which may be a collection) and the value formanyis passed.
-
marshmallow.decorators.pre_load(fn=None, pass_many=False)[source]¶ Register a method to invoke before deserializing an object. The method receives the data to be deserialized and returns the processed data.
By default, receives a single datum at a time, transparently handling the
manyargument passed to the Schema. Ifpass_many=True, the raw data (which may be a collection) and the value formanyis passed.
-
marshmallow.decorators.tag_processor(tag_name, fn, pass_many, **kwargs)[source]¶ Tags decorated processor function to be picked up later.
Note
Currently ony works with functions and instance methods. Class and static methods are not supported.
Returns: Decorated function if supplied, else this decorator with its args bound.
-
marshmallow.decorators.validates(field_name)[source]¶ Register a field validator.
Parameters: field_name (str) – Name of the field that the method validates.
-
marshmallow.decorators.validates_schema(fn=None, pass_many=False, pass_original=False, skip_on_field_errors=False)[source]¶ Register a schema-level validator.
By default, receives a single object at a time, regardless of whether
many=Trueis passed to theSchema. Ifpass_many=True, the raw data (which may be a collection) and the value formanyis passed.If
pass_original=True, the original data (before unmarshalling) will be passed as an additional argument to the method.If
skip_on_field_errors=True, this validation method will be skipped whenever validation errors have been detected when validating fields.
Validators¶
Validation classes for various types of data.
-
class
marshmallow.validate.ContainsOnly(choices, labels=None, error=None)[source]¶ Validator which succeeds if
valueis a sequence and each element in the sequence is also in the sequence passed aschoices.Parameters:
-
class
marshmallow.validate.Email(error=None)[source]¶ Validate an email address.
Parameters: error (str) – Error message to raise in case of a validation error. Can be interpolated with {input}.
-
class
marshmallow.validate.Equal(comparable, error=None)[source]¶ Validator which succeeds if the
valuepassed to it is equal tocomparable.Parameters: - comparable – The object to compare to.
- error (str) – Error message to raise in case of a validation error.
Can be interpolated with
{input}and{other}.
-
class
marshmallow.validate.Length(min=None, max=None, error=None, equal=None)[source]¶ Validator which succeeds if the value passed to it has a length between a minimum and maximum. Uses len(), so it can work for strings, lists, or anything with length.
Parameters: - min (int) – The minimum length. If not provided, minimum length will not be checked.
- max (int) – The maximum length. If not provided, maximum length will not be checked.
- equal (int) – The exact length. If provided, maximum and minimum length will not be checked.
- error (str) – Error message to raise in case of a validation error.
Can be interpolated with
{input},{min}and{max}.
-
class
marshmallow.validate.NoneOf(iterable, error=None)[source]¶ Validator which fails if
valueis a member ofiterable.Parameters: - iterable (iterable) – A sequence of invalid values.
- error (str) – Error message to raise in case of a validation error. Can be
interpolated using
{input}and{values}.
-
class
marshmallow.validate.OneOf(choices, labels=None, error=None)[source]¶ Validator which succeeds if
valueis a member ofchoices.Parameters: - choices (iterable) – A sequence of valid values.
- labels (iterable) – Optional sequence of labels to pair with the choices.
- error (str) – Error message to raise in case of a validation error. Can be
interpolated with
{input},{choices}and{labels}.
-
options(valuegetter=<class 'str'>)[source]¶ Return a generator over the (value, label) pairs, where value is a string associated with each choice. This convenience method is useful to populate, for instance, a form select field.
Parameters: valuegetter – Can be a callable or a string. In the former case, it must be a one-argument callable which returns the value of a choice. In the latter case, the string specifies the name of an attribute of the choice objects. Defaults to str()orunicode().
-
class
marshmallow.validate.Predicate(method, error=None, **kwargs)[source]¶ Call the specified
methodof thevalueobject. The validator succeeds if the invoked method returns an object that evaluates to True in a Boolean context. Any additional keyword argument will be passed to the method.Parameters: - method (str) – The name of the method to invoke.
- error (str) – Error message to raise in case of a validation error.
Can be interpolated with
{input}and{method}. - kwargs – Additional keyword arguments to pass to the method.
-
class
marshmallow.validate.Range(min=None, max=None, error=None)[source]¶ Validator which succeeds if the value it is passed is greater or equal to
minand less than or equal tomax. Ifminis not specified, or is specified asNone, no lower bound exists. Ifmaxis not specified, or is specified asNone, no upper bound exists.Parameters: - min – The minimum value (lower bound). If not provided, minimum value will not be checked.
- max – The maximum value (upper bound). If not provided, maximum value will not be checked.
- error (str) – Error message to raise in case of a validation error.
Can be interpolated with
{input},{min}and{max}.
-
class
marshmallow.validate.Regexp(regex, flags=0, error=None)[source]¶ Validate
valueagainst the provided regex.Parameters: - regex – The regular expression string to use. Can also be a compiled regular expression pattern.
- flags – The regexp flags to use, for example re.IGNORECASE. Ignored
if
regexis not a string. - error (str) – Error message to raise in case of a validation error.
Can be interpolated with
{input}and{regex}.
-
class
marshmallow.validate.URL(relative=False, error=None, schemes=None, require_tld=True)[source]¶ Validate a URL.
Parameters: - relative (bool) – Whether to allow relative URLs.
- error (str) – Error message to raise in case of a validation error.
Can be interpolated with
{input}. - schemes (set) – Valid schemes. By default,
http,https,ftp, andftpsare allowed. - require_tld (bool) – Whether to reject non-FQDN hostnames
Utility Functions¶
Utility methods for marshmallow.
-
marshmallow.utils.callable_or_raise(obj)[source]¶ Check that an object is callable, else raise a
ValueError.
-
marshmallow.utils.decimal_to_fixed(value, precision)[source]¶ Convert a
Decimalto a fixed-precision number as a string.
-
marshmallow.utils.float_to_decimal(f)[source]¶ Convert a floating point number to a Decimal with no loss of information. See: http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq
-
marshmallow.utils.from_datestring(datestring)[source]¶ Parse an arbitrary datestring and return a datetime object using dateutils’ parser.
-
marshmallow.utils.from_iso(datestring, use_dateutil=True)[source]¶ Parse an ISO8601-formatted datetime string and return a datetime object.
Use dateutil’s parser if possible and return a timezone-aware datetime.
-
marshmallow.utils.from_iso_time(timestring, use_dateutil=True)[source]¶ Parse an ISO8601-formatted datetime string and return a datetime.time object.
-
marshmallow.utils.from_rfc(datestring, use_dateutil=True)[source]¶ Parse a RFC822-formatted datetime string and return a datetime object.
Use dateutil’s parser if possible.
https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime
-
marshmallow.utils.get_func_args(func)[source]¶ Given a callable, return a list of argument names. Handles
functools.partialobjects and callable objects.
-
marshmallow.utils.get_value(key, obj, default=<marshmallow.missing>)[source]¶ Helper for pulling a keyed value off various types of objects
-
marshmallow.utils.is_collection(obj)[source]¶ Return True if
objis a collection type, e.g list, tuple, queryset.
-
marshmallow.utils.is_indexable_but_not_string(obj)[source]¶ Return True if
objis indexable but isn’t a string.
-
marshmallow.utils.is_instance_or_subclass(val, class_)[source]¶ Return True if
valis either a subclass or instance ofclass_.
-
marshmallow.utils.is_iterable_but_not_string(obj)[source]¶ Return True if
objis an iterable object that isn’t a string.
-
marshmallow.utils.is_keyed_tuple(obj)[source]¶ Return True if
objhas keyed tuple behavior, such as namedtuples or SQLAlchemy’s KeyedTuples.
-
marshmallow.utils.isoformat(dt, localtime=False, *args, **kwargs)[source]¶ Return the ISO8601-formatted UTC representation of a datetime object.
-
marshmallow.utils.local_rfcformat(dt)[source]¶ Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset.
-
marshmallow.utils.pluck(dictlist, key)[source]¶ Extracts a list of dictionary values from a list of dictionaries.
>>> dlist = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}] >>> pluck(dlist, 'id') [1, 2]
-
marshmallow.utils.pprint(obj, *args, **kwargs)[source]¶ Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of
marshmallow.Schema.dump().
-
marshmallow.utils.rfcformat(dt, localtime=False)[source]¶ Return the RFC822-formatted representation of a datetime object.
Parameters: - dt (datetime) – The datetime.
- localtime (bool) – If
True, return the date relative to the local timezone instead of UTC, displaying the proper offset, e.g. “Sun, 10 Nov 2013 08:23:45 -0600”
Marshalling¶
Utility classes and values used for marshalling and unmarshalling objects to and from primitive types.
Warning
This module is treated as private API. Users should not need to use this module directly.
-
class
marshmallow.marshalling.Marshaller(prefix='')[source]¶ Callable class responsible for serializing data and storing errors.
Parameters: prefix (str) – Optional prefix that will be prepended to all the serialized field names. -
serialize(obj, fields_dict, many=False, accessor=None, dict_class=<class 'dict'>, index_errors=True, index=None)[source]¶ Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields.
Parameters: - obj – The actual object(s) from which the fields are taken from
- fields_dict (dict) – Mapping of field names to
Fieldobjects. - many (bool) – Set to
Trueifdatashould be serialized as a collection. - accessor (callable) – Function to use for getting values from
obj. - dict_class (type) – Dictionary class used to construct the output.
- index_errors (bool) – Whether to store the index of invalid items in
self.errorswhenmany=True. - index (int) – Index of the item being serialized (for storing errors) if
serializing a collection, otherwise
None.
Returns: A dictionary of the marshalled data
Changed in version 1.0.0: Renamed from
marshal.
-
-
class
marshmallow.marshalling.Unmarshaller[source]¶ Callable class responsible for deserializing data and storing errors.
New in version 1.0.0.
-
deserialize(data, fields_dict, many=False, partial=False, dict_class=<class 'dict'>, index_errors=True, index=None)[source]¶ Deserialize
databased on the schema defined byfields_dict.Parameters: - data (dict) – The data to deserialize.
- fields_dict (dict) – Mapping of field names to
Fieldobjects. - many (bool) – Set to
Trueifdatashould be deserialized as a collection. - partial (bool|tuple) – Whether to ignore missing fields. If its value is an iterable, only missing fields listed in that iterable will be ignored.
- dict_class (type) – Dictionary class used to construct the output.
- index_errors (bool) – Whether to store the index of invalid items in
self.errorswhenmany=True. - index (int) – Index of the item being serialized (for storing errors) if
serializing a collection, otherwise
None.
Returns: A dictionary of the deserialized data.
-
Class Registry¶
A registry of Schema classes. This allows for string
lookup of schemas, which may be used with
class:fields.Nested.
Warning
This module is treated as private API. Users should not need to use this module directly.
-
marshmallow.class_registry.get_class(classname, all=False)[source]¶ Retrieve a class from the registry.
Raises: marshmallow.exceptions.RegistryError if the class cannot be found or if there are multiple entries for the given class name.
-
marshmallow.class_registry.register(classname, cls)[source]¶ Add a class to the registry of serializer classes. When a class is registered, an entry for both its classname and its full, module-qualified path are added to the registry.
Example:
class MyClass: pass register('MyClass', MyClass) # Registry: # { # 'MyClass': [path.to.MyClass], # 'path.to.MyClass': [path.to.MyClass], # }
Exceptions¶
Exception classes for marshmallow-related errors.
-
exception
marshmallow.exceptions.MarshmallowError[source]¶ Base class for all marshmallow-related errors.
-
exception
marshmallow.exceptions.RegistryError[source]¶ Raised when an invalid operation is performed on the serializer class registry.
-
exception
marshmallow.exceptions.ValidationError(message, field_names=None, fields=None, data=None, **kwargs)[source]¶ Raised when validation fails on a field. Validators and custom fields should raise this exception.
Parameters: - message – An error message, list of error messages, or dict of error messages.
- field_names (list) – Field names to store the error on.
If
None, the error is stored in its default location. - fields (list) –
Fieldobjects to which the error applies.
-
field_names= None¶ List of field_names which failed validation.
-
fields= None¶ List of field objects which failed validation.
-
messages= None¶ String, list, or dictionary of error messages. If a
dict, the keys will be field names and the values will be lists of messages.