Schema¶
- class marshmallow.schema.Schema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]¶
Base schema class with which to define custom schemas.
Example usage:
import datetime as dt from dataclasses import dataclass from marshmallow import Schema, fields @dataclass class Album: title: str release_date: dt.date class AlbumSchema(Schema): title = fields.Str() release_date = fields.Date() album = Album("Beggars Banquet", dt.date(1968, 12, 6)) schema = AlbumSchema() data = schema.dump(album) data # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}
- Parameters:
only – Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters.
exclude – Blacklist of the declared 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.many – Should be set to
Trueifobjis a collection so that the object will be serialized to a list.context – Optional context passed to
fields.Methodandfields.Functionfields.load_only – Fields to skip during serialization (write-only fields)
dump_only – Fields to skip during deserialization (read-only fields)
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE.
Changed in version 3.0.0:
prefixparameter removed.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.Classes:
Meta()Options object for a Schema.
alias of
SchemaOptsalias of
OrderedSetMethods:
dump(obj, *[, many])Serialize an object to native Python data types according to this Schema's fields.
dumps(obj, *args[, many])Same as
dump(), except return a JSON-encoded string.from_dict(fields, *[, name])Generate a
Schemaclass given a dictionary of fields.get_attribute(obj, attr, default)Defines how to pull values from an object to serialize.
handle_error(error, data, *, many, **kwargs)Custom error handler function for the schema.
load(data, *[, many, partial, unknown])Deserialize a data structure to an object defined by this Schema's fields.
loads(json_data, *[, many, partial, unknown])Same as
load(), except it takes a JSON string as input.on_bind_field(field_name, field_obj)Hook to modify a field when it is bound to the
Schema.validate(data, *[, many, partial])Validate
dataagainst the schema, returning a dictionary of validation errors.Attributes:
Overrides for default schema-level error messages
Dictionary mapping field_names ->
Fieldobjects- class Meta[source]¶
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 theexplicitly declared fields.
additionalandfieldsare mutually-exclusive options.
include: Dictionary of additional fields to include in the schema. It isusually 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: Default format forDatefields.datetimeformat: Default format forDateTimefields.timeformat: Default format forTimefields.ordered: IfTrue, output ofSchema.dumpwill be acollections.OrderedDict.index_errors: IfTrue, errors dictionaries will include the indexof 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 deserializationunknown: Whether to exclude, include, or raise an error for unknownfields in the data. Use
EXCLUDE,INCLUDEorRAISE.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- dump(obj: Any, *, many: bool | None = None)[source]¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize
objas a collection. IfNone, the value forself.manyis used.
- Returns:
Serialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)[source]¶
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize
objas a collection. IfNone, the value forself.manyis used.
- Returns:
A
jsonstring
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: Dict[str, str] = {}¶
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type[source]¶
Generate a
Schemaclass given a dictionary of fields.from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in
Nestedfields.- Parameters:
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)[source]¶
Defines how to pull values from an object to serialize.
New in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
objandattr.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)[source]¶
Custom error handler function for the schema.
- Parameters:
error – The
ValidationErrorraised during (de)serialization.data – The original input data.
many – Value of
manyon dump or load.partial – Value of
partialon load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives
manyandpartial(on deserialization) as keyword arguments.
- load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)[source]¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters:
data – The data to deserialize.
many – Whether to deserialize
dataas a collection. IfNone, the value forself.manyis used.partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE. IfNone, the value forself.unknownis used.
- Returns:
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)[source]¶
Same as
load(), except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize
objas a collection. IfNone, the value forself.manyis used.partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE. IfNone, the value forself.unknownis used.
- Returns:
Deserialized data
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None[source]¶
Hook to modify a field when it is bound to the
Schema.No-op by default.
- set_class¶
alias of
OrderedSetMethods:add(key)Add an element.
clear()This is slow (creates N new iterators!) but effective.
discard(key)Remove an element.
isdisjoint(other)Return True if two sets have a null intersection.
pop([last])Return the popped value.
remove(value)Remove an element.
- validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None) dict[str, list[str]][source]¶
Validate
dataagainst the schema, returning a dictionary of validation errors.- Parameters:
data – The data to validate.
many – Whether to validate
dataas a collection. IfNone, the value forself.manyis used.partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
New in version 1.1.0.