python - 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-'
}
有没有办法在棉花糖中指定这个?
解决方案
您可以使用@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)
以上应该在第一次打印时失败,在第二次打印时成功。在此处查看演示。
推荐阅读
- android - REACT NATIVE : 高度大小的项目
- amazon-web-services - 从命令访问更新的 lambda 版本:`aws lambda publish-version`
- windows - 2018 年 4 月更新后,如何在 Windows 10 上将文件扩展名的“默认应用程序”设置为“.exe”
- python - 如果存在,如何检查一个数组中的元素是否存在于另一个数组中使用Python打印计数
- swift - Firebase 评论未出现在数据库中
- amazon-web-services - Dockerize Web 应用程序
- javascript - 如何在猫头鹰旋转木马中放箭?
- r - 将数据框转换为 rmarkdown 的参数列表
- react-native - 使用expo推送通知,iOS设备无法接收推送
- python - 用beautifulsoup attrs 提取href