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

简单python验证库,它报告所有验证错误而不是第一个失败?,python,jsonschema,Python,Jsonschema,我试过了 而且,这两种方法都很简单,在验证方面也很好,但是它们都做基于异常的错误报告,也就是说,它们在第一个错误时失败。是否有一种方法可以获取Volupturous或Schema中数据的所有验证错误 我发现它似乎与一些需求相匹配,但没有对对象键进行验证,也没有基于自定义函数的验证(例如lambdas) 要求: def myMethod(input_dict): #input_dict should abide to this schema -> # { 'id' : INT

我试过了 而且,这两种方法都很简单,在验证方面也很好,但是它们都做基于异常的错误报告,也就是说,它们在第一个错误时失败。是否有一种方法可以获取Volupturous或Schema中数据的所有验证错误

我发现它似乎与一些需求相匹配,但没有对对象键进行验证,也没有基于自定义函数的验证(例如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 ]
我以前用过,它完全可以做你想做的事情。如果您愿意,它还可以基于异常报告错误,但是您也可以遍历文档中发现的所有验证错误。我已经编写了一个简短的示例程序,它使用您的模式(请参阅)并打印出所有发现的错误

编辑:我已经更改了脚本,所以它现在使用了一个自定义的验证器,允许您进行自己的验证,代码应该是自解释的。您可以在
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

我想您的需求现在已经被这个脚本满足了。

实际上,
volupluous
确实提供了这个功能,尽管在文档中并不明显,但它只是调用
MultipleInvalid.errors
。该函数从验证器返回捕获的
无效的
异常列表

e、 g


你能举个例子说明你需要从这样一个图书馆得到什么吗?如果验证失败,您希望继续而不是停止执行,这听起来像是一个日志作业。@BurhanKhalid当然,我想验证方法的输入并返回所有验证错误。似乎在说,如果验证器引发
无效
异常,它们将被捕获并关联到路径。它不是你想要的吗?(我只是好奇,我从来没有使用过它)我不知道这些库是如何阻止你这样做的?@Burnkhalid这些库在看到第一个错误时会引发异常,我想收集模式的所有验证错误。但是jsonschema不满足问题中提到的要求“没有对象键的验证和基于自定义函数的验证(如lambdas)。”我在代码中添加了自定义验证,现在它应该可以执行您想要的操作(当您推出自己的架构和验证程序时)。另请参见人性化子模块:。例如,
验证带有人性化错误(数据、架构)
$ 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'
try:

    schema({...})

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