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": [lambda x: x == "bar"]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

# Success!

其中,validation是我们的验证规则(检查点),dictionary是要检查的数据,将validation与dictionary作为函数validate的参数,即可获得验证结果。我们可以根据实际需要定义更为复杂的验证规则。

三、几个可以直接使用的验证器

1、Equals

值匹配验证

passes = {

"foo": "bar"

}

failures = {

"foo": "barrr"

}

validation = {

"foo": [Equals("bar")]

}

>>> validate(validation, passes)

ValidationResult(valid=True, errors={})

# Success!

>>> validate(validation, failures)

ValidationResult(valid=False, errors={'foo': ["must be equal to 'bar'"]})

# Failure!

2、Required

默认情况下,key是可选择的。如果一个key在validation中,但是不在dictionary中,那么在数据验证时,默认跳过。如果想要确保某个key存在,可以用Required。

dictionary1 = {

"foo": "bar"

}

dictionary2 = {

}

validation = {

"foo": [Required, Equals("bar")]

}

>>> validate(validation, dictionary1)

ValidationResult(valid=True, errors={})

>>> validate(validation, dictionary2)

ValidationResult(valid=False, errors={'foo': 'must be present'})

3、Truthy

验证dictionary中的值是否是python中的真值,python中的真值包括 True, 非0整数,非空列表,非空字符串等。

dictionary = {

"foo": 1

}

validation = {

"foo": [Required, Truthy()]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

4、Range

验证dictionary中的值是否在Range范围内。

dictionary = {

"foo": 10

}

failure = {

"foo": 12

}

validation = {

"foo": [Required, Range(1, 11)]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

>>> validate(validation, failure)

ValidationResult(valid=False, errors={'foo': ['must fall between 1 and 11']})

5、Pattern

验证数据格式。

dictionary = {

"foo": "30%"

}

failure = {

"foo": "99.0"

}

validation = {

"foo": [Required, Pattern("\d\d\%")]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

# Success!

>>> validate(validation, failure)

ValidationResult(valid=False, errors={'foo': ['must match regex pattern \\d\\d\\

%']})

# failure

6、In

检查dictionary中的值是否在一个集合中

dictionary = {

"foo": "spam"

}

failure = {

"foo": "beans"

}

validation = {

"foo": [Required, In(["spam", "eggs", "bacon"])]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

>>> validate(validation, failure)

ValidationResult(valid=False, errors={'foo': ['must match regex pattern \\d\\d\\

%']})

7、Not

Not可以放在其他验证器前面,表示相反的验证内容。

dictionary = {

"foo": "beans"

}

validation = {

"foo": [Required, Not(In(["spam", "eggs", "bacon"]))]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

dictionary = {

"foo": 10

}

validation = {

"foo": [Required, Not(Range(1, 11))]

}

>>> validate(validation, dictionary)

ValidationResult(valid=False, errors={'foo': ['must not fall between 1 and 11']})

8、InstanceOf

检查dictionary中的值是否是一个基类或它的子类的实例。

dictionary = {

"foo": u"i'm_a_unicode_string"

}

failure = {

"foo": object

}

validation = {

"foo": [Required, InstanceOf(basestring)]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

>>> validate(validation, failure)

ValidationResult(valid=False, errors={'foo': ['must be an instance of str or its

subclasses']})

9、SubclassOf

检查dictionary中的值是否是一个基类的子类,特别强调,这里说的是基类的子类,而不是类的实例。

dictionary = {

"foo": unicode

}

failure = {

"foo": "bar"

}

validation = {

"foo": [Required, SubclassOf(basestring)]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

>>> validate(validation, failure)

ValidationResult(valid=False, errors={'foo': ['must be a subclass of basestring']})

10、Length

检查dictionary中的value至少有minimum 个元素,至多有maximum个元素,其中第一个参数为minimum ,第二个参数maximum可选。

dictionary = {

"foo": [1, 2, 3, 4, 5]

}

validation = {

"foo": [Length(0, maximum=5)]

}

>>> validate(validation, dictionary)

ValidationResult(valid=True, errors={})

dictionary = {

"foo": [1, 2, 3, 4, 5]

}

validation = {

"foo": [Length(6, maximum=10)]

}

>>> validate(validation, dictionary)

ValidationResult(valid=False, errors={'foo': ['must be between 6 and 10 elements in length']})

四、条件验证

在某些情况下,我们可能需要先验证某项数据,在这项数据验证通过时再进行下一步的验证,这时,我们可以使用条件验证,If(validator, Then(validation))

pet = {

"name": "whiskers",

"type": "cat"

}

cat_name_rules = {

"name": [In(["whiskers", "fuzzy", "tiger"])]

}

dog_name_rules = {

"name": [In(["spot", "ace", "bandit"])]

}

validation = {

"type": [

If(Equals("cat"), Then(cat_name_rules)),

If(Equals("dog"), Then(dog_name_rules))

]

}

>>> validate(validation, pet)

ValidationResult(valid=True, errors={})

五、嵌套验证

有时我们需要验证的数据不是简单的结构,而是一个嵌套结构。上栗子:

validator = {

"foo": [Required, Equals(1)],

"bar": [Required, {

"baz": [Required, Equals(2)],

"qux": [Required, {

"quux": [Required, Equals(3)]

}]

}

]

}

test_case = {

"foo": 1,

"bar": {

"baz": 2,

"qux": {

"quux": 3

}

}

}

>>> validate(validator, test_case)

ValidationResult(valid=True, errors={})

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐