我正在使用带有python-3.8稳定的json 1.3.2版来验证将用于发送cerberus请求的json数据。我在使用dependencies规则时遇到了问题。我的对象有一个字段request_type和一个包含更多数据的可选字段payload。只有在['CREATE', 'AMEND']中有request_type的对象才有payload。当我运行验证时,我得到一个与payload中的一个字段相关的错误。下面是我正在运行的代码:
from cerberus import Validator
request = {
"request_type": "CREATE",
"other_field_1": "whatever",
"other_field_2": "whatever",
"payload": {
"id": "123456",
"jobs": [
{
"duration": 1800,
"other_field_1": "whatever",
"other_field_2": "whatever"
}
]
}
}
schema = {
'request_type': {
'type': 'string',
'allowed': ['CREATE', 'CANCEL', 'AMEND'],
'required': True,
'empty': False
},
'other_field_1': {'type': 'string', },
'other_field_2': {'type': 'string', },
'payload': {
'required': False,
'schema': {
'id': {
'type': 'string',
'regex': r'[A-Za-z0-9_-]`',
'minlength': 1, 'maxlength': 32,
'coerce': str
},
'jobs': {
'type': 'list',
'schema': {
'duration': {
'type': 'integer', 'min': 0,
'required': True, 'empty': False,
},
'other_field_1': {'type': 'string', },
'other_field_2': {'type': 'string', },
}
}
},
'dependencies': {'request_type': ['CREATE', 'AMEND']},
}
}
validator = Validator(schema, purge_unknown=True)
if validator.validate(request):
print('The request is valid.')
else:
print(f'The request failed validation: {validator.errors}')这就是我得到的错误:
"RuntimeError: There's no handler for 'duration' in the 'validate' domain."我是不是做错了什么?
对于上下文,我设法使用完全相同的规则来进行验证,但是我没有使用dependencies,而是使用了两个独立的模式,分别名为payload_schema和no_payload_schema。在payload_schema中,我将request_type的允许值设置为['CREATE', 'AMEND'],在no_payload_schema中,我将允许值设置为['CANCEL']。我对两个模式都运行了验证,如果它们都没有通过,我就会抛出一个错误。这听起来有点老生常谈,我想知道如何使用dependencies规则来做到这一点。
发布于 2020-03-13 04:17:22
注意用于映射和序列的difference between schema。因为您要求jobs字段的类型是list,所以它的值不会被检查为映射。您将需要此模式:
{"jobs":
{
{"type": "list", "schema":
{
"type": "dict", "schema": {"duration": ...}
}
}
}
}schema规则的这种模糊性将在Cerberus的下一个主要版本中得到解决。出于可读性的考虑,可以使用带有复杂验证模式的schema- and rule set-registries。
通常情况下,建议使用最少的示例来获得支持。
https://stackoverflow.com/questions/60524853
复制相似问题