python - RuntimeError:“验证”域中没有 [insert_filed_name] 的处理程序
问题描述
我正在使用cerberus
带有python-3.8
stable 的 v1.3.2 来验证将用于发送 http 请求的 json 数据。我在使用该dependencies
规则时遇到问题。我的对象有一个字段和一个包含更多数据request_type
的可选字段。payload
只有具有request_type
in的对象['CREATE', 'AMEND']
才有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
规则来做到这一点。
解决方案
注意用于映射和序列的模式之间的区别。该jobs
字段的值不会被检查为映射,因为您要求它是list
类型。你需要这个模式:
{"jobs":
{
{"type": "list", "schema":
{
"type": "dict", "schema": {"duration": ...}
}
}
}
}
规则的这种模糊性schema
将在 Cerberus 的下一个主要版本中得到解决。为了可读性,可以使用具有复杂验证模式的模式和规则集注册表。
通常建议用最少的例子来寻求支持。
推荐阅读
- javascript - 添加触摸输入并让图像在一段时间后消失
- ruby - 无法访问类属性
- android - 广告评分、Google Console 和 12+,“广告加载失败:3”和“G”
- javascript - 如何创建一个反应原生 ios 共享扩展应用程序
- mongodb - Mongo:获取每个组的第一个具有匹配条件的文档
- usb - usb cdc 示例 + PWM 导致硬故障错误
- excel - UDF 在 VBA 中工作,返回 #REF!在工作簿中
- dart - 重建父级时调用子级初始化方法 - 颤动
- java - 更改数组列表中的元素
- javascript - 如何在特定显示器的双显示器设置中打开浏览器窗口?