Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple python validation library which reports all validation errors instead of first failed?

I have tried voluptuous and schema, both of which are simple and great in validation, but they both do exception-based error reporting, i.e. they fail on first error. Is there a way I can get all validation errors of data in Voluptuous or Schema?

I found jsonschema that seems matching some of the requirements, but does not have validation for object keys, and custom function based validation (e.g. lambdas).

Requirement:

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 ]
like image 311
DhruvPathak Avatar asked Jul 01 '13 12:07

DhruvPathak


People also ask

What are validation checks in Python?

Introduction to Python Validation Whenever the user accepts an input, it needs to be checked for validation which checks if the input data is what we are expecting.

What is JSON validation error?

This means that you have an error with the JSON data structure that you included in the body of your request and that it doesn't follow the format in which we expected to receive it. In order to know exactly what is wrong with your JSON data, you will need to validate it using a JSON schema.

What is a schema in Python?

schema is a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.


1 Answers

Actually Voluptuous does provide this functionality, though not obvious in the docs, it is simply a call to MultipleInvalid.errors. The function returns a list of caught Invalid exceptions from your validators.

e.g.

try:

    schema({...})

except MultipleInvalid as e:
    # get the list of all `Invalid` exceptions caught
    print e.errors  
like image 148
chutsu Avatar answered Oct 29 '22 01:10

chutsu