首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RuntimeError:在“validate”域中没有[insert_filed_name]的处理程序

RuntimeError:在“validate”域中没有[insert_filed_name]的处理程序
EN

Stack Overflow用户
提问于 2020-03-04 19:17:18
回答 1查看 494关注 0票数 1

我正在使用带有python-3.8稳定的json 1.3.2版来验证将用于发送cerberus请求的json数据。我在使用dependencies规则时遇到了问题。我的对象有一个字段request_type和一个包含更多数据的可选字段payload。只有在['CREATE', 'AMEND']中有request_type的对象才有payload。当我运行验证时,我得到一个与payload中的一个字段相关的错误。下面是我正在运行的代码:

代码语言:javascript
复制
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}')

这就是我得到的错误:

代码语言:javascript
复制
"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规则来做到这一点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-13 04:17:22

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

代码语言:javascript
复制
{"jobs": 
  {
    {"type": "list", "schema": 
      {
        "type": "dict", "schema": {"duration": ...}
      }
    }
  }
}

schema规则的这种模糊性将在Cerberus的下一个主要版本中得到解决。出于可读性的考虑,可以使用带有复杂验证模式的schema- and rule set-registries

通常情况下,建议使用最少的示例来获得支持。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60524853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档