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 ]
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With