简单的python验证库报告所有验证错误而不是第一次失败?

时间:2013-07-01 12:18:32

标签: python jsonschema

我试过了 voluptuousschema,这两者在验证方面都很简单且很好,但它们都执行基于异常的错误报告,即它们在第一次出错时失败。有没有办法可以在Voluptuous或Schema中获得数据的所有验证错误?

我发现jsonschema似乎符合某些要求,但没有验证对象键和基于自定义函数的验证(例如lambdas)。

要求:

def myMethod(input_dict):

   #input_dict should abide to this schema -> 
   # { 'id' : INT , 'name':'string 5-10 chars','hobbies': LIST OF STRINGS }
   # for incorrect input like
   # {'id': 'hello','name':'Dhruv','hobbies':[1,2,3] }
   # I should be able to return all errors like
   # ['id' is not integer,'hobbies' is not list of strings ]

2 个答案:

答案 0 :(得分:13)

实际上Voluptuous确实提供了此功能,虽然在文档中并不明显,但它只是对MultipleInvalid.errors的调用。该函数返回验证器中捕获的Invalid例外列表。

e.g。

try:

    schema({...})

except MultipleInvalid as e:
    # get the list of all `Invalid` exceptions caught
    print e.errors  

答案 1 :(得分:2)

我之前使用过jsonschema,它完全可以做你想做的事情。如果需要,它还会执行基于异常的错误报告,但您也可以遍历文档中找到的所有验证错误,我编写了一个使用您的架构的简短示例程序(请参阅Json Schema V3 Spec)并打印出所有发现错误。

编辑:我已经更改了脚本,所以它现在使用自定义验证器,允许您自己进行验证,代码应该是自我解释的。您可以在jsonschema上查找extend信息来源以及如何扩展/编码验证码。

#!/usr/bin/env python2

from jsonschema import Draft3Validator
from jsonschema.exceptions import ValidationError
from jsonschema.validators import extend
import json
import sys

schema = {
    "type": "object",
    "required": True,
    "additinalProperties": False,
    "properties": {
        "id": {
            "type": "integer",
            "required": True
        },
        "name": {
            "type": "string",
            "required": True,
            "minLength": 5,
            "maxLength": 10
        },
        "hobbies": {
            "type": "array",
            "customvalidator": "hobbies",
            "required": True,
            "items": {
                "type": "string"
            }
        }
    }
}


def hobbiesValidator(validator, value, instance, schema):
    if 'Foo' not in instance:
        yield ValidationError("You need to like Foo")

    for field in instance:
        if not validator.is_type(instance, "string"):
            yield ValidationError("A hobby needs to be a string")
        elif len(field) < 5:
            err = "I like only hobbies which are len() >= 5, {} doesn't"
            yield ValidationError(err.format(value))


def anotherHobbiesValidator(validator, value, instance, schema):
    pass


myCustomValidators = {
    'hobbies': hobbiesValidator,
    'anotherHobbies': anotherHobbiesValidator
}


def customValidatorDispatch(validator, value, instance, schema):
    if value not in myCustomValidators:
        err = '{} is unknown, we only know about: {}'
        yield ValidationError(err.format(value, ', '.join(myCustomValidators.keys())))
    else:
        errors = myCustomValidators[value](validator, value, instance, schema)
        for error in errors:
            yield error


def myMethod(input_dict):
    customValidator = extend(Draft3Validator, {'customvalidator': customValidatorDispatch}, 'MySchema')
    validator = customValidator(schema)

    errors = [e for e in validator.iter_errors(input_dict)]
    if len(errors):
        return errors

    # do further processing here
    return []

if __name__ == '__main__':
    data = None
    try:
        f = open(sys.argv[1], 'r')
        data = json.loads(f.read())
    except Exception, e:
        print "Failed to parse input: {}".format(e)
        sys.exit(-1)

    errors = myMethod(data)

    if not len(errors):
        print "Input is valid!"
    else:
        print "Input is not valid, errors:"
        for error in errors:
            print "Err: ", error

输入无效:

$ cat invalid-input.json
{
    "id": "hello",
    "name": "Dhruv",
    "hobbies": [
        1, 2, 3
    ]
}

$ ./validate.py invalid-input.json
Input is not valid, errors:
Err:  1 is not of type 'string'

Failed validating 'type' in schema['properties']['hobbies']['items']:
    {'type': 'string'}

On instance['hobbies'][0]:
    1
Err:  2 is not of type 'string'

Failed validating 'type' in schema['properties']['hobbies']['items']:
    {'type': 'string'}

On instance['hobbies'][1]:
    2
Err:  3 is not of type 'string'

Failed validating 'type' in schema['properties']['hobbies']['items']:
    {'type': 'string'}

On instance['hobbies'][2]:
    3
Err:  You need to like Foo

Failed validating 'customvalidator' in schema['properties']['hobbies']:
    {'customvalidator': 'hobbies',
     'items': {'type': 'string'},
     'required': True,
     'type': 'array'}

On instance['hobbies']:
    [1, 2, 3]
Err:  A hobby needs to be a string

Failed validating 'customvalidator' in schema['properties']['hobbies']:
    {'customvalidator': 'hobbies',
     'items': {'type': 'string'},
     'required': True,
     'type': 'array'}

On instance['hobbies']:
     [1, 2, 3]
Err:  A hobby needs to be a string

Failed validating 'customvalidator' in schema['properties']['hobbies']:
    {'customvalidator': 'hobbies',
     'items': {'type': 'string'},
     'required': True,
     'type': 'array'}

On instance['hobbies']:
    [1, 2, 3]
Err:  A hobby needs to be a string

Failed validating 'customvalidator' in schema['properties']['hobbies']:
    {'customvalidator': 'hobbies',
     'items': {'type': 'string'},
     'required': True,
     'type': 'array'}

On instance['hobbies']:
    [1, 2, 3]
Err:  u'hello' is not of type 'integer'

Failed validating 'type' in schema['properties']['id']:
    {'required': True, 'type': 'integer'}

On instance['id']:
    u'hello'

我认为您的要求现在由此脚本填充。