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

我正在构建一个 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-'

}

有没有办法在棉花糖中指定这个?


HUH函数
浏览 84回答 1
1回答

斯蒂芬大帝

您可以使用@pre_load将这些字段放在一个extras字段上(例如),该字段可能包含您想要的任何数据,请参阅有关Extending Schema的 Marshmallow 文档。from marshmallow import Schema, fields, ValidationError, pre_loadclass 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)以上应该在第一次打印时失败,在第二次打印时成功。在此处查看演示。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python