为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUH函数 2022-11-09 14:47:55
我正在构建一个 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-'}有没有办法在棉花糖中指定这个?
查看完整描述

1 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

您可以使用@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)

以上应该在第一次打印时失败,在第二次打印时成功。在此处查看演示



查看完整回答
反对 回复 2022-11-09
  • 1 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信