省略棉花糖中无效嵌套多个字段的实例



在棉花糖中,是否可以省略未通过验证的嵌套架构实例而不会使父级失败?例如,一个 Atom 源可以有许多条目。如果一个条目缺少必填字段,是否可以省略该条目,以便源及其正确解析的条目通过验证,而不会失败的条目?

from marshmallow import Schema

class Feed(Schema):
"""Atom/RSS feed."""
...
entries = fields.Nested('Entry', many=True)
...
class Entry(Schema):
"""Article of an Atom/RSS feed."""
...
title = fields.String(required=True)
link = fields.Url(required=True)
...

验证源之前

...
"entries": [
{
"title": "Title A",
"link": "http://httpbin.org/status/200"
},
{
"title": "",
"link": "",
},
{
"title": "Title C",
"link": "http://httpbin.org/status/200"
},
]
...

验证源后

...
"entries": [
{
"title": "Title A",
"link": "http://httpbin.org/status/200"
},
{
"title": "Title C",
"link": "http://httpbin.org/status/200"
},
]
...

pre_load装饰器可用于过滤嵌套字段,但我假设每个嵌套架构都反序列化两次:一次在pre_load期间,一次在加载期间。

class Feed(Schema):
...
entries = fields.Nested('Entry', many=True)
...
@pre_load
def filter_entries(self, data, **kwargs):
schema = Entry()
filtered = []
for entry in data['entries']:
try:
filtered.append(schema.load(entry))
except ValidationError:
continue
data['entries'] = filtered
return data

相关内容

  • 没有找到相关文章

最新更新