python - 如何通过 cerberus 验证其字段可以是 dict 或 dict 列表的数据?
问题描述
我需要验证从用户收到的字典
问题是一个字段既可以是字典也可以是字典列表。我如何用 cerberus 验证这一点?
像一个例子我尝试这个模式:
v = Validator(
{
'v': {
'type': ['dict', 'list'],
'schema': {
'type': 'dict',
'schema': {'name': {'type': 'string'}}
}
}
}
)
但是当我在测试数据上尝试时,我收到错误:
v.validate({'v': {'name': '2'}}) # False
# v.errors: {'v': ['must be of dict type']}
错误:
{'v': ['must be of dict type']}
解决方案
我猜内部schema
是用于为字典键的值定义类型和规则(如果v
是字典):
v = Validator(
{
'v': {
'type': ['dict', 'list'],
'schema': {
'name': {'type': 'string'}
}
}
}
)
print(v.validate({'v': {'name': '2'}}))
print(v.errors)
或对于列表值,如果v
是列表:
v = Validator(
{
'v': {
'type': ['dict', 'list'],
'schema': {
'type': 'integer',
}
}
}
)
print(v.validate({'v': [1]}))
print(v.errors)
两种情况的正输出:
True
{}
推荐阅读
- c# - 使用 GtkSharp (GTK#) 在 C# 中拖放
- javascript - 可以公开我的 Google/OAuth 密钥吗?
- javascript - javascript何时决定将对象更改为字符串
- javascript - 如何使用 offset 和 limit 参数向 musicBrainz api 发出浏览请求
- javascript - 如何在重定向到网站部分之前关闭菜单
- go - 如何干净地向函数添加参数
- c# - 使用 azure 服务总线在 Blazor 应用程序和微服务 api 之间进行通信
- flutter - 参数类型'AsyncSnapshot
>' 不能分配给参数类型'DocumentSnapshot