validator.py是一个数据验证工具,确保数据符合一定的规则。一个validation是一个字典,对于字典中的每一个键,包含一个规则列表。
先看两个简单的例子,就可以大致了解validator的用法啦,也可以从中体会到validator与validators的不同之处。
from validator import Required, Not, Truthy, Blank, Range, Equals, In, validate
# let's say that my dictionary needs to meet the following rules...
rules = {
"foo": [Required, Equals(123)], # foo must be exactly equal to 123
"bar": [Required, Truthy()], # bar must be equivalent to True
"baz": [In(["spam", "eggs", "bacon"])], # baz must be one of these options
"qux": [Not(Range(1, 100))] # qux must not be a number between 1 and 100 inclusive
}
# then this following dict would pass:
passes = {
"foo": 123,
"bar": True, # or a non-empty string, or a non-zero int, etc...
"baz": "spam",
"qux": 101
}
>>> validate(rules, passes)
ValidationResult(valid=True, errors={})
# but this one would fail
fails = {
"foo": 321,
"bar": False, # or 0, or [], or an empty string, etc...
"baz": "barf",
"qux": 99
}
>>> validate(rules, fails)
ValidationResult(valid=False, errors={'baz': ["must be one of ['spam', 'eggs', 'bacon']"], 'foo': ['must be equal to 123'], 'bar': ['must be True-equivalent value'], 'qux': ['must not fall between 1 and 100']})
一、安装
1、稳定版本安装
$ pip install validator.py
2、最新版本
二、开启验证之旅
我们可以自定义验证器,先上例子:
dictionary = {
"foo": "bar"
}
validation = {
"foo"