如何通过cerberus验证其字段可以是字典或字典列表的数据?
How to validate by cerberus the data the field of which can be a dict, or list of 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)
OR 对于列表值,如果 v
是一个列表:
v = Validator(
{
'v': {
'type': ['dict', 'list'],
'schema': {
'type': 'integer',
}
}
}
)
print(v.validate({'v': [1]}))
print(v.errors)
两种情况下的正输出:
True
{}
我尝试了以下方法,似乎工作正常:
'oneof':[
{
'type': 'dict',
'schema':{
'field1': {
'type':'string',
'required':True
},
'field2': {
'type':'string',
'required':False
}
}
},
{
'type': 'list',
'schema': {
'type': 'dict',
'schema':{
'field1': {
'type':'string',
'required':True
},
'field2': {
'type':'string',
'required':False
}
}
}
}
]
对于遇到此问题的任何其他人,我希望这可能有用。我花了一些时间才完全理解。
我需要验证从用户那里收到的字典
问题是一个字段既可以是字典也可以是字典列表。我如何用 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)
OR 对于列表值,如果 v
是一个列表:
v = Validator(
{
'v': {
'type': ['dict', 'list'],
'schema': {
'type': 'integer',
}
}
}
)
print(v.validate({'v': [1]}))
print(v.errors)
两种情况下的正输出:
True
{}
我尝试了以下方法,似乎工作正常:
'oneof':[
{
'type': 'dict',
'schema':{
'field1': {
'type':'string',
'required':True
},
'field2': {
'type':'string',
'required':False
}
}
},
{
'type': 'list',
'schema': {
'type': 'dict',
'schema':{
'field1': {
'type':'string',
'required':True
},
'field2': {
'type':'string',
'required':False
}
}
}
}
]
对于遇到此问题的任何其他人,我希望这可能有用。我花了一些时间才完全理解。