亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Marshmallow 模式:允許任何額外字段,只要其名稱與模式匹配

Marshmallow 模式:允許任何額外字段,只要其名稱與模式匹配

HUH函數 2022-11-09 14:47:55
我正在構建一個 API 端點,并使用 Marshmallow 進行輸入驗證和封送處理。我想接受的對象之一有一些特定的字段,但只要字段名稱以 . 開頭,也會接受其他字段x-。例如:{  "name": "Bob Paulson",  // a strict, required field  "email": "[email protected]",  // 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": "[email protected]"}


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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號