API¶
Error Handler¶
Media Handler¶
Middleware¶
Spec¶
Docstring¶
Document¶
- class document.base.BaseDocument(meta=None, **kwargs)[source]¶
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
Agent¶
- class document.agent.catalog.AgentCatalogDocument(meta=None, **kwargs)[source]¶
Represents an agent in the catalog.
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
- class document.agent.instance.AgentInstanceDocument(meta=None, **kwargs)[source]¶
Represents an agent instance installed in an execution environment.
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
eBPF Program¶
Connection¶
- class document.connection.ConnectionDocument(meta=None, **kwargs)[source]¶
Represents an connection between execution environments and network links.
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
Data¶
- class document.data.DataDocument(meta=None, **kwargs)[source]¶
Represents the stored data.
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
Execution Environment¶
- class document.exec_env.ExecEnvDocument(meta=None, **kwargs)[source]¶
Represents an execution environment.
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
- class document.exec_env.ExecEnvTypeDocument(meta=None, **kwargs)[source]¶
Type of execution environment. Example: virtual machine or container.
- delete(using=None, index=None, **kwargs)¶
Delete the instance in elasticsearch.
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.delete
unchanged.
- classmethod get(id, using=None, index=None, **kwargs)¶
Retrieve a single document from elasticsearch using it’s
id
.- Parameters
id –
id
of the document to be retrievedindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
Any additional keyword arguments will be passed to
Elasticsearch.get
unchanged.
- classmethod init(index=None, using=None)¶
Create the index and populate the mappings in elasticsearch.
- classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)¶
Retrieve multiple document by their
id
s. Returns a list of instances in the same order as requested.- Parameters
docs – list of
id
s of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.htmlindex – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
missing – what to do when one of the documents requested is not found. Valid options are
'none'
(useNone
),'raise'
(raiseNotFoundError
) or'skip'
(ignore the missing document).
Any additional keyword arguments will be passed to
Elasticsearch.mget
unchanged.
- save(using=None, index=None, validate=True, skip_empty=True, **kwargs)¶
Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns
True
if this operations resulted in new document being created.- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
validate – set to
False
to skip validating the documentskip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
Any additional keyword arguments will be passed to
Elasticsearch.index
unchanged.:return operation result created/updated
- classmethod search(using=None, index=None)¶
Create an
Search
instance that will search over thisDocument
.
- to_dict(include_meta=False, skip_empty=True)¶
Serialize the instance into a dictionary so that it can be saved in elasticsearch.
- Parameters
include_meta – if set to
True
will include all the metadata (_index
,_id
etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances intoelasticsearch.helpers.bulk
.skip_empty – if set to
False
will cause empty values (None
,[]
,{}
) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.
- update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, **fields)¶
Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:
doc = MyDocument(title='Document Title!') doc.save() doc.update(title='New Document Title!')
- Parameters
index – elasticsearch index to use, if the
Document
is associated with an index this can be omitted.using – connection alias to use, defaults to
'default'
detect_noop – Set to
False
to disable noop detection.refresh – Control when the changes made by this request are visible to search. Set to
True
for immediate effect.retry_on_conflict – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.
doc_as_upsert – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value
:return operation result noop/updated
Network Link¶
Lib¶
Response¶
Reader¶
Resource¶
Agent¶
eBPF Program¶
Execution Environment¶
Network Link¶
Connection¶
Data¶
Schema¶
- class schema.base.BaseSchema(*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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.
Agent¶
Catalog¶
- class schema.agent.catalog.AgentCatalogSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents an agent in the catalog.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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
.
- doc¶
- 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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.agent.catalog.AgentCatalogActionSchema(*, 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]¶
Agent action.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.catalog.AgentCatalogActionConfigSchema(*, 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]¶
Agent action configuration.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.catalog.AgentCatalogParameterSchema(*, 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]¶
Agent parameter.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.catalog.AgentCatalogParameterConfigSchema(*, 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]¶
Agent parameter configuration.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.catalog.AgentCatalogResourceSchema(*, 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]¶
Agent resource.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.catalog.AgentCatalogResourceConfigSchema(*, 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]¶
Agent resource configuration.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.
Instance¶
- class schema.agent.instance.AgentInstanceSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents an agent instance installed in an execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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
.
- doc¶
- 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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.agent.instance.AgentInstanceOperationSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents the operations to perform with the agent instance installed in an execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.agent.instance.AgentInstanceActionSchema(*, 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]¶
Action of the agent instance installed in an execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.instance.AgentInstanceParameterSchema(*, 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]¶
Parameter of the agent instance installed in an execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.agent.instance.AgentInstanceResourceSchema(*, 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]¶
Resource of the agent instance installed in an execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.
eBPF Program¶
Catalog¶
Instance¶
Execution Environment¶
- class schema.exec_env.LCPSchema(*, 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]¶
Configuration of the LCP running in the execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.exec_env.ExecEnvSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents an execution environment.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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
.
- doc¶
alias of
document.exec_env.ExecEnvDocument
- 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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.exec_env.ExecEnvTypeSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents an execution environment type.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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
.
- doc¶
- 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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.
Network Link¶
Connection¶
- class schema.connection.ConnectionSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents an connection between execution environments and network links.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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
.
- doc¶
- 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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.
Data¶
- class schema.data.DataSchema(*args, method=None, check_unique_id=False, **kwargs)[source]¶
Represents the stored data.
- 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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
.
- doc¶
alias of
document.data.DataDocument
- 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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponse'>, item_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.
Query Request¶
Response¶
- class schema.response.ExceptionResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.BaseResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.BadRequestResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.ConflictResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.ContentResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.CreatedResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.NoContentResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.NotAcceptableResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.NotFoundResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.NotModifiedResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.OkResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.ResetContentResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.UnauthorizedResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.UnprocessableEntityResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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.UnsupportedMediaTypeResponseSchema(*, 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
marshmallow.schema.SchemaOpts
- _bind_field(field_name: str, field_obj: marshmallow.fields.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: marshmallow.error_store.ErrorStore, many: bool = False, partial=False, unknown='raise', index=None) Union[marshmallow.schema._T, List[marshmallow.schema._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[marshmallow.schema._T, Iterable[marshmallow.schema._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.
- fields¶
Dictionary mapping field_names ->
Field
objects
- classmethod from_dict(fields: Dict[str, Union[marshmallow.fields.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: marshmallow.exceptions.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: marshmallow.fields.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’.