API¶
Error Handler¶
Media Handler¶
- class api.media_handler.XML_Handler(dumps=None, loads=None)[source]¶
- deserialize(stream, content_type, content_length)[source]¶
Deserialize the
falcon.Request
body.By default, this method raises an instance of
NotImplementedError
. Therefore, it must be overridden in order to work with WSGI apps. Child classes can ignore this method if they are only to be used with ASGI apps, as long as they overridedeserialize_async()
.Note:
The JSON media handler is an exception in requiring the implementation of the sync version also for ASGI apps. See the this section for more details.
- Args:
stream (object): Readable file-like object to deserialize. content_type (str): Type of request content. content_length (int): Length of request content.
- Returns:
object: A deserialized object.
- deserialize_async(stream, content_type, content_length)¶
Deserialize the
falcon.Request
body.This method is similar to
deserialize()
except that it is asynchronous. The default implementation adapts the synchronousdeserialize()
method viaio.BytesIO
. For improved performance, media handlers should override this method.- Note:
By default, the
deserialize()
method raises an instance ofNotImplementedError
. Therefore, child classes must either overridedeserialize()
ordeserialize_async()
in order to be compatible with ASGI apps.- Args:
stream (object): Asynchronous file-like object to deserialize. content_type (str): Type of request content. content_length (int): Length of request content.
- Returns:
object: A deserialized object.
- serialize(media, content_type) bytes ¶
Serialize the media object on a
falcon.Response
.By default, this method raises an instance of
NotImplementedError
. Therefore, it must be overridden in order to work with WSGI apps. Child classes can ignore this method if they are only to be used with ASGI apps, as long as they overrideserialize_async()
.Note:
The JSON media handler is an exception in requiring the implementation of the sync version also for ASGI apps. See the this section for more details.
- Args:
media (object): A serializable object. content_type (str): Type of response content.
- Returns:
bytes: The resulting serialized bytes from the input object.
- serialize_async(media, content_type) bytes ¶
Serialize the media object on a
falcon.Response
.This method is similar to
serialize()
except that it is asynchronous. The default implementation simply callsserialize()
. If the media object may be awaitable, or is otherwise something that should be read asynchronously, subclasses must override the default implementation in order to handle that case.- Note:
By default, the
serialize()
method raises an instance ofNotImplementedError
. Therefore, child classes must either overrideserialize()
orserialize_async()
in order to be compatible with ASGI apps.- Args:
media (object): A serializable object. content_type (str): Type of response content.
- Returns:
bytes: The resulting serialized bytes from the input object.
- class api.media_handler.YAML_Handler(dumps=None, loads=None)[source]¶
- deserialize(stream, content_type, content_length)[source]¶
Deserialize the
falcon.Request
body.By default, this method raises an instance of
NotImplementedError
. Therefore, it must be overridden in order to work with WSGI apps. Child classes can ignore this method if they are only to be used with ASGI apps, as long as they overridedeserialize_async()
.Note:
The JSON media handler is an exception in requiring the implementation of the sync version also for ASGI apps. See the this section for more details.
- Args:
stream (object): Readable file-like object to deserialize. content_type (str): Type of request content. content_length (int): Length of request content.
- Returns:
object: A deserialized object.
- deserialize_async(stream, content_type, content_length)¶
Deserialize the
falcon.Request
body.This method is similar to
deserialize()
except that it is asynchronous. The default implementation adapts the synchronousdeserialize()
method viaio.BytesIO
. For improved performance, media handlers should override this method.- Note:
By default, the
deserialize()
method raises an instance ofNotImplementedError
. Therefore, child classes must either overridedeserialize()
ordeserialize_async()
in order to be compatible with ASGI apps.- Args:
stream (object): Asynchronous file-like object to deserialize. content_type (str): Type of request content. content_length (int): Length of request content.
- Returns:
object: A deserialized object.
- serialize(media, content_type) bytes ¶
Serialize the media object on a
falcon.Response
.By default, this method raises an instance of
NotImplementedError
. Therefore, it must be overridden in order to work with WSGI apps. Child classes can ignore this method if they are only to be used with ASGI apps, as long as they overrideserialize_async()
.Note:
The JSON media handler is an exception in requiring the implementation of the sync version also for ASGI apps. See the this section for more details.
- Args:
media (object): A serializable object. content_type (str): Type of response content.
- Returns:
bytes: The resulting serialized bytes from the input object.
- serialize_async(media, content_type) bytes ¶
Serialize the media object on a
falcon.Response
.This method is similar to
serialize()
except that it is asynchronous. The default implementation simply callsserialize()
. If the media object may be awaitable, or is otherwise something that should be read asynchronously, subclasses must override the default implementation in order to handle that case.- Note:
By default, the
serialize()
method raises an instance ofNotImplementedError
. Therefore, child classes must either overrideserialize()
orserialize_async()
in order to be compatible with ASGI apps.- Args:
media (object): A serializable object. content_type (str): Type of response content.
- Returns:
bytes: The resulting serialized bytes from the input object.
Middleware¶
Spec¶
Docstring¶
Lib¶
- lib.http.HTTP_Status¶
alias of
HTTPStatus
Response¶
Reader¶
Resource¶
- class resource.code.Code_Resource[source]¶
- on_delete(req, resp, id=None)[source]¶
Inject code at run-time in the local environment. — summary: Code injection description: Inject code at run-time in the local environment. parameters:
name: payload required: true in: body schema:
type: array items: Code_Request_Schema
tags: [code] responses:
- 200:
description: Codes inject correctly. schema:
- oneOf:
type: array items: Created_Response
- 204:
description: No content to inject codes based on the request. schema: No_Content_Response_Schema
- 400:
description: Request not valid. schema: Bad_Request_Response_Schema
- 401:
description: Authentication failed. schema: Unauthorized_Response_Schema
- 406:
description: Request validation failed. schema: Not_Acceptable_Response_Schema
- 422:
description: Not possible to inject one or more codes. schema:
type: array items:
- oneOf:
Created_Response_Schema
Unprocessable_Entity_Response_Schema
- 500:
description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema
- on_post(req, resp, id=None)[source]¶
Inject code at run-time in the local environment. — summary: Code injection description: Inject code at run-time in the local environment. parameters:
name: payload required: true in: body schema:
type: array items: Code_Request_Schema
tags: [code] responses:
- 200:
description: Codes inject correctly. schema:
- oneOf:
type: array items: Created_Response
- 204:
description: No content to inject codes based on the request. schema: No_Content_Response_Schema
- 400:
description: Request not valid. schema: Bad_Request_Response_Schema
- 401:
description: Authentication failed. schema: Unauthorized_Response_Schema
- 406:
description: Request validation failed. schema: Not_Acceptable_Response_Schema
- 422:
description: Not possible to inject one or more codes. schema:
type: array items:
- oneOf:
Created_Response_Schema
Unprocessable_Entity_Response_Schema
- 500:
description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema
- on_put(req, resp, id=None)[source]¶
Update the injected code at run-time in the local environment. — summary: Update injected code description: Update the injected code at run-time in the local environment. parameters:
name: payload required: true in: body schema:
type: array items: Code_Request_Schema
tags: [code] responses:
- 200:
description: All injected code correctly updated. schema:
type: array items: Ok_Response_Schema
- 204:
description: No content to update codes based on the request. schema: No_Content_Response_Schema
- 304:
description: Update for one or more codes not necessary. schema:
type: array items:
- oneOf:
Ok_Response_Schema
Not_Modified_Response
- 400:
description: Request not valid. schema: Bad_Request_Response_Schema
- 401:
description: Authentication failed. schema: Unauthorized_Response_Schema
- 406:
description: Request validation failed. schema: Not_Acceptable_Response_Schema
- 415:
description: Media type not supported. schema: Unsupported_Media_Type_Response_Schema
- 422:
description: Not possible to update one or more codes based on the request. schema:
type: array items:
- oneOf:
Ok_Response_Schema
Not_Modified_Response
Unprocessable_Entity_Response_Schema
- 500:
description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema
- class resource.config.Config_Resource[source]¶
- on_post(req, resp)[source]¶
Apply configuration changes to the local environment. — summary: Configuration update description: Apply configuration changes to the local environment. tags: [config] parameters:
name: payload required: true in: body schema:
type: array items: Config_Request_Schema
- responses:
- 200:
description: Configuration changed correctly. schema:
- oneOf:
type: array items: Created_Response
- 204:
description: No content to configure based on the request. schema: No_Content_Response_Schema
- 400:
description: Request not valid. schema: Bad_Request_Response_Schema
- 401:
description: Authentication failed. schema: Unauthorized_Response_Schema
- 406:
description: Request validation failed. schema: Not_Acceptable_Response_Schema
- 422:
description: Not possible to change one or more configurations. schema:
type: array items:
- oneOf:
Created_Response_Schema
Unprocessable_Entity_Response_Schema
- 500:
description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema
- class resource.status.Status_Resource[source]¶
- on_get(req, resp)[source]¶
Get info about the status of the LCP in the execution environment. — summary: Status info description: Get info about the status of the LCP in the execution environment. tags: [status] responses:
- 200:
description: Status data of the LCP. schema: Status_Response_Schema
- 400:
description: Request not valid. schema: Bad_Request_Response_Schema
- 401:
description: Authentication failed. schema: Unauthorized_Response_Schema
- 406:
description: Request validation failed. schema: Not_Acceptable_Response_Schema
- 500:
description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema
- on_post(req, resp)[source]¶
Set the last heartbeat. — summary: Status set. description: Set the last heartbeat. tags: [status] responses:
- 200:
description: Heartbeat with CB-Manager correctly executed. schema: Status_Response_Schema
- 400:
description: Request not valid. schema: Bad_Request_Response_Schema
- 401:
description: Authentication failed. schema: Unauthorized_Response_Schema
- 406:
description: Request validation failed. schema: Not_Acceptable_Response_Schema
- 500:
description: Server not available to satisfy the request. schema: Internal_Server_Error_Response_Schema
Schema¶
- class schema.base.Base_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)[source]¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
Code¶
- class schema.code.Code_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Request for code endpoint.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
Config¶
Request¶
- class schema.config.Config_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Request for config endpoint.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.config.Config_Action_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Action part in a single item of the code request.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.config.Config_Parameter_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Parameter part in a single item of the code request.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.config.Config_Resource_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Resource part in a single item of the code request.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
Response¶
- class schema.config.Config_Action_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Action part in a single item of the config response.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.config.Config_Parameter_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Parameter part in a single item of the config response.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.config.Config_Parameter_Value_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Parameter value part in a single item of the config response.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.config.Config_Resource_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Resource part in a single item of the config response.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
Status¶
- class schema.status.Status_Request_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Response for status endpoint.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.status.Status_Response_Schema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Response for status endpoint.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data, response_type=<class 'lib.response.Ok_Response'>, id=None)¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
Response¶
- class schema.response.Exception_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Base_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
Response for the item creation.
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Bad_Request_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Conflict_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Content_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Created_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.No_Content_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Not_Acceptable_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Not_Found_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Not_Modified_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Ok_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Reset_Content_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Unauthorized_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Unprocessable_Entity_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
- class schema.response.Unsupported_Media_Type_Response_Schema(*, only: Optional[Union[Sequence[str], Set[str]]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)[source]¶
- 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 theexplicitly declared fields.
additional
andfields
are 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 for Date <fields.Date> fields.datetimeformat
: Default format for DateTime <fields.DateTime> fields.render_module
: Module to use for loads <Schema.loads> and dumps <Schema.dumps>.Defaults to json from the standard library.
ordered
: If True, order serialization output according to theorder in which fields were declared. Output of Schema.dump will be a collections.OrderedDict.
index_errors
: If True, 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, INCLUDE or RAISE.
register
: Whether to register the Schema with marshmallow’s internalclass registry. Must be True if you intend to refer to this Schema by class name in Nested fields. Only set this to False when memory usage is critical. Defaults to True.
- OPTIONS_CLASS¶
alias of
SchemaOpts
- _bind_field(field_name: str, field_obj: Field) None ¶
Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was specified in
class Meta
.
- static _call_and_store(getter_func, data, *, field_name, error_store, index=None)¶
Call
getter_func
withdata
as its argument, and store any ValidationErrors.- Parameters
getter_func (callable) – Function for getting the serialized/deserialized value from
data
.data – The data passed to
getter_func
.field_name (str) – Field name.
index (int) – Index of the item being validated, if validating a collection, otherwise None.
- _deserialize(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, error_store: ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[_T, List[_T]] ¶
Deserialize
data
.- Parameters
data (dict) – The data to deserialize.
error_store (ErrorStore) – Structure to store errors.
many (bool) – True if
data
should be deserialized as a collection.partial (bool|tuple) – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE.
index (int) – Index of the item being serialized (for storing errors) if serializing a collection, otherwise None.
- Returns
A dictionary of the deserialized data.
- _do_load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, postprocess: bool = True)¶
Deserialize data, returning the deserialized result. This method is private API.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If True, all fields will be allowed missing. If None, the value for self.partial is used.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
postprocess – Whether to run post_load methods..
- Returns
Deserialized data
- _init_fields() None ¶
Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API.
- _normalize_nested_options() None ¶
Apply then flatten nested schema options. This method is private API.
- _serialize(obj: Union[_T, Iterable[_T]], *, many: bool = False)¶
Serialize
obj
.- Parameters
obj – The object(s) to serialize.
many (bool) – True if
data
should be serialized as a collection.
- Returns
A dictionary of the serialized data
Changed in version 1.0.0: Renamed from
marshal
.
- dump(obj: Any, *, many: Optional[bool] = None)¶
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A dict of serialized data
- Return type
dict
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: Optional[bool] = None, **kwargs)¶
Same as
dump()
, except return a JSON-encoded string.- Parameters
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns
A
json
string- Return type
str
New in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)
duple. AValidationError
is raised ifobj
is invalid.
- error_messages = {}¶
Overrides for default schema-level error messages
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[Field, type]], *, name: str = 'GeneratedSchema') type ¶
Generate a Schema class 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 Nested fields.
- Parameters
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
repr
for the class.
New in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)¶
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
obj
andattr
.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)¶
Custom error handler function for the schema.
- Parameters
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
many
on dump or load.partial – Value of
partial
on load.
New in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- load(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None)¶
Deserialize a data structure to an object defined by this Schema’s fields.
- Parameters
data – The data to deserialize.
many – Whether to deserialize data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- loads(json_data: str, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None, unknown: Optional[str] = None, **kwargs)¶
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 obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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, INCLUDE or RAISE. If None, the value for self.unknown is 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. AValidationError
is raised if invalid data are passed.
- on_bind_field(field_name: str, field_obj: Field) None ¶
Hook to modify a field when it is bound to the Schema.
No-op by default.
- validate(data: Mapping, *, many: Optional[bool] = None, partial: Optional[Union[bool, Sequence[str], Set[str]]] = None) Dict[str, List[str]] ¶
Validate data against the schema, returning a dictionary of validation errors.
- Parameters
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nested
fields 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.
Utils¶
Datetime¶
- utils.datetime.FORMAT = '%Y/%m/%dT%H:%M:%S'¶
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
Exception¶
JSON¶
Log¶
Sequence¶
Signal¶
- utils.signal.send_tree(pid, sig=Signals.SIGTERM, include_parent=True, timeout=None, on_terminate=None)[source]¶
Kill a process tree (including grandchildren) with signal “sig” and return a (gone, still_alive) tuple.
“on_terminate”, if specified, is a callback function which is called as soon as a child terminates.
String¶
- utils.string.format = <bound method Formatter.format of <utils.string.Formatter object>>¶