棉花糖模式:允许任何额外字段,只要其名称与模式匹配

Marshmallow schema: allow any extra field as long as its name matches a pattern

我正在构建一个 API 端点,并使用 Marshmallow 进行输入验证和编组。我要接受的对象之一有一些特定的字段,但只要字段名称以 x- 开头,也会接受其他字段。例如:

{
  "name": "Bob Paulson",  // a strict, required field
  "email": "bob@example.com",  // a strict, required field
  "x-dob": "1980-10-11" // not a part of the explicit schema but accepted because it begins with 'x-'
}

有没有办法在 Marshmallow 中指定它?

您可以使用 @pre_load 将这些字段放在 extras 字段上(例如),其中可能包含您想要的任何数据,请参阅有关 Extending Schema 的 Marshmallow 文档。

from marshmallow import Schema, fields, ValidationError, pre_load


class PersonSchema(Schema):
    name = fields.Str()
    email = fields.Str()
    extra = fields.Dict()

    @pre_load
    def unwrap_envelope(self, data, **kwargs):
        extra = {}
        rest = {}
        for k, v in data.items():
          if k.startswith('x-'):
            extra[k] = v
          else:
            rest[k] = v
        return {'extra':extra,**rest}


sch = PersonSchema()
person_data = {"name": "John Doe", "email": "jdoe@email.com"}

try:
  res1 = sch.load({**person_data,"dob": "1980-11-11"})
  print(res1)
except ValidationError as err:
  print(err.messages)

try:
  res2 = sch.load({**person_data,"x-dob": "1980-11-11"})
  print(res2)
except ValidationError as err:
  print(err.messages)

以上应该在第一次打印时失败,在第二次打印时成功。 See a demo here.