Monday, December 22, 2014

Must validate

your Python dictionary against a certain set of rules you know it must comply with (schema)?Voluptuous is a Python data validation library! (Despite the name)

Say you've got a dictionary from json.loads. Just define your schema and check if what you've got is good:
from voluptuous import Schema, Required, All, Length, Range
schema = Schema({
    Required('q'): All(str, Length(min=1)),
    Required('per_page', default=5): All(int, Range(min=1, max=20)),
        'page': All(int, Range(min=0)),
    })
"q" is required:
from voluptuous import MultipleInvalid, Invalid
try:
    schema({})
    print "MultipleInvalid not raised"
except MultipleInvalid as e:
    print e
required key not provided @ data['q']
...must be a string:
try:
    schema({'q': 123})
    print "MultipleInvalid not raised"
except MultipleInvalid as e:
    print e
expected str for dictionary value @ data['q']
...and must be at least one character long:
try:
    schema({'q': ''})
    print "MultipleInvalid not raised"
except MultipleInvalid as e:
    print e
length of value must be at least 1 for dictionary value @ data['q']
Note how per_page is assigned its default value:
try:
    s = schema({'q': '#topic'})
    print "s = {0}".format(s)
except MultipleInvalid as e:
    print e
s = {'q': '#topic', 'per_page': 5}

No comments:

Post a Comment