RuntimeError:“验证”域中没有用于[insert_filed_name]的处理程序

问题描述 投票:1回答:1

我正在使用cerberus v1.3.2和python-3.8稳定版来验证将用于发送http请求的json数据。使用dependencies规则时出现问题。我的对象有一个字段request_type和一个可选字段payload,其中包含更多数据。只有在request_type中具有['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_schemano_payload_schema的架构。在payload_schema中,将request_type的允许值设置为['CREATE', 'AMEND'],在no_payload_schema中,将允许的值设置为['CANCEL']。我在两个模式上都运行验证,如果两个都不通过,则会引发错误。这听起来有点不客气,我想了解如何使用dependencies规则来做到这一点。

python cerberus
1个回答
0
投票

记住difference between schema用于映射和序列。 jobs字段的值不会作为映射检查,因为您要求它是list类型。您将需要以下模式:

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

schema规则的歧义将在Cerberus的下一个主要版本中解决。为了便于阅读,可以将schema- and rule set-registries与复杂的验证模式结合使用。

通常建议以最少的示例来寻求支持。

© www.soinside.com 2019 - 2024. All rights reserved.