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

问题描述 投票:0回答:1

marshmallow中是否可以忽略嵌套验证失败的实例而不使父实例失败?例如,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"
  },
]
...

验证Feed后

...
"entries": [
  {
    "title": "Title A",
    "link": "http://httpbin.org/status/200"
  },
  {
    "title": "Title C",
    "link": "http://httpbin.org/status/200"
  },
]
...
python python-3.x marshmallow
1个回答
0
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.