首页 > 解决方案 > RuntimeError:“验证”域中没有 [insert_filed_name] 的处理程序

问题描述

我正在使用cerberus带有python-3.8stable 的 v1.3.2 来验证将用于发送 http 请求的 json 数据。我在使用该dependencies规则时遇到问题。我的对象有一个字段和一个包含更多数据request_type的可选字段。payload只有具有request_typein的对象['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规则来做到这一点。

标签: pythoncerberus

解决方案


注意用于映射和序列的模式之间的区别。jobs字段的值不会被检查为映射,因为您要求它是list类型。你需要这个模式:

{"jobs": 
  {
    {"type": "list", "schema": 
      {
        "type": "dict", "schema": {"duration": ...}
      }
    }
  }
}

规则的这种模糊性schema将在 Cerberus 的下一个主要版本中得到解决。为了可读性,可以使用具有复杂验证模式的模式和规则集注册表。

通常建议用最少的例子来寻求支持。


推荐阅读