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)
以上应该在第一次打印时失败,在第二次打印时成功。在此处查看演示。
添加回答
举报