Python数据验证库(三)voluptuous

继续记录最近学习的python数据验证工具。
voluptuousvalidator的使用比较相似,注意是validator,不是validatorsvalidatorvalidators是两个不同的python数据验证的库。

Voluptuous的目标:
1、简洁
2、支持复杂的数据结构
3、提供有价值的错误信息

一、安装

$ pip install voluptuous

二、数据验证

1、和validator类似,为了验证数据,我们需要先定义一个模式scheme.

>>> from voluptuous import Schema
>>> schema = Schema({
      'q': str,
      'per_page': int,
      'page': int,
})

这个模式要求待检查的数据,字段"q"需要时str类型,字段"per_page"需要是int类型,字段"page"需要是int类型。

如果我们要验证的数据是

data = { 
 "q": "hello world", 
 "per_page": 20,
 "page": 10
}

只需要

>>> schema(data)
{'q': 'hello world', 'per_page': 20, 'page': 10}

如果验证通过,则返回验证的数据。那么,如果验证的参数不能通过呢?我们来看一个验证失败的例子。

failure_data = { 
 "q": "hello world", 
 "per_page": "hi",
 "page": 10
}
>>> schema(failure_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 221, i
n __call__
    return self._compiled([], data)
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 538, i
n validate_dict
    return base_validate(path, iteritems(data), out)
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 370, i
n validate_mapping
    raise er.MultipleInvalid(errors)
voluptuous.error.MultipleInvalid: expected int for dictionary value @ data['per_
page']

这里字段 “per_page”的值是字符串,不是int类型,验证失败,程序报错
但是有时在一个程序里,我们会做多个验证,我们只是希望得到每一个验证的结果,成功or失败,不希望因为一处失败,而影响后面程序的执行。这种情况下,我们可以在程序中捕获异常,得到错误信息。

demo.py

from voluptuous import Schema, MultipleInvalid

schema = Schema({
      'q': str,
      'per_page': int,
      'page': int,
})

failure_data = { 
 "q": "hello world", 
 "per_page": "hi",
 "page": 10
}

try:
    schema(failure_data)
except MultipleInvalid as e:
    print e.errors

>>> python demo.py
[TypeInvalid('expected int',)]

e.errors可以很清晰知道验证时,发生了类型验证错误。

2、在验证的过程中,有时我们需要数据必须含有某一个字段,这时可以使用Required.
以上面的例子为例 :

schema = Schema({
      'q': str,
      'per_page': int,
      'page': int,
})

data = { 
 "q": "hello world", 
 "page": 10
}

>>> schema(data)
{'q': 'hello world', 'page': 10}

data中没有'per_page'字段,验证依然是成功的;如果我们需要data中必须含有'per_page'字段,那么schema可以这样定义:

from voluptuous import Required
schema = Schema({
      'q': str,
      Required('per_page'): int,
      'page': int,
})

data = { 
 "q": "hello world", 
 "page": 10
}

>>>schema(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 221, i
n __call__
    return self._compiled([], data)
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 538, i
n validate_dict
    return base_validate(path, iteritems(data), out)
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 370, i
n validate_mapping
    raise er.MultipleInvalid(errors)
voluptuous.error.MultipleInvalid: required key not provided @ data['per_page']

此时data中缺少'per_page'字段,程序报错。

3、通常我们不仅需要判断数据字段是否存在,类型是否正确,还会对字符串或列表长度进行验证,对数据值的范围进行验证。我们可以将对一个字段的多项验证用All封装起来。

>>> from voluptuous import 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)),
... })

举两个验证失败的例子:
(1) 数据中必须含有'q'字段

>>> from voluptuous import MultipleInvalid
>>>try:
    schema({})
except MultipleInvalid as e:
    exc = e
>>> exc.errors
[RequiredFieldInvalid('required key not provided',)]

(2) 字段page的值必须是一个大于等于0的整数。

try:
    schema({'q': '#topic', 'per_page': 'one'})
except MultipleInvalid as e:
    exc = e
>>> exc.errors
[TypeInvalid('expected int',)]

三、定义schemas

voluptuous的一个优点是不仅仅可以验证字典数据,也可以验证一些其他类型的数据。

1、字面值(Literals)

仅仅匹配模式schema中定义的值与数据data中的值是否相等。

>>> schema = Schema(1)
>>> schema(1)
1
>>> schema(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 225, i
n __call__
    raise er.MultipleInvalid([e])
voluptuous.error.MultipleInvalid: not a valid value
>>> schema = Schema('a string')
>>> schema('a string')
'a string'
2、类型(types)
>>> schema = Schema(int)
>>> schema(1)
1
>>> schema('one')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python27\lib\site-packages\voluptuous\schema_builder.py", line 225, i
n __call__
    raise er.MultipleInvalid([e])
voluptuous.error.MultipleInvalid: expected int
3、URL’s
>>> from voluptuous import Url
>>> schema = Schema(Url())
>>> schema('http://w3.org')
'http://w3.org'
>>> try:
...   schema('one')
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "expected a URL"
True
4、列表(Lists)

模式列表中定义了一些合法的值,被检查的数据列表中的每一个值都需要在模式列表中被定义。

>>> schema = Schema([1, 'a', 'string'])
>>> schema([1])
[1]
>>> schema([1, 1, 1])
[1, 1, 1]
>>> schema(['a', 1, 'string', 1, 'string'])
['a', 1, 'string', 1, 'string']

如果想要定义一个列表,可以包含所有python合法值,可以使用list

>>> schema = Schema(list)
>>> schema([])
[]
>>> schema([1, 2])
[1, 2]

注意不是使用[]

>>> schema = Schema([])
>>> try:
...   schema([1])
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value"
True
>>> schema([])
[]
5、自定义函数
>>> from datetime import datetime
>>> def Date(fmt='%Y-%m-%d'):
...   return lambda v: datetime.strptime(v, fmt)
>>> schema = Schema(Date())
>>> schema('2013-03-03')
datetime.datetime(2013, 3, 3, 0, 0)
>>> try:
...   schema('2013-03')
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "not a valid value"
True
6、字典

待验证的数据中每一个键值对需要在字典中已定义,否则,验证失败。

>>> schema = Schema({1: 'one', 2: 'two'})
>>> schema({1: 'one'})
{1: 'one'}

如果我们要验证的数据中有额外的键值对,并且这种情况不认为是错误的,可以这样设置。

>>> from voluptuous import ALLOW_EXTRA
>>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)
>>> schema({1: 2, 2: 3})
{1: 2, 2: 3}

如果想要移除额外的键,可以使用Schema(..., extra=REMOVE_EXTRA):

>>> from voluptuous import REMOVE_EXTRA
>>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)
>>> schema({1: 2, 2: 3})
{2: 3}

默认情况下,在字典模式schema中定义的key-value对,待验证的数据中不需要完全覆盖。

>>> schema = Schema({1: 2, 3: 4})
>>> schema({3: 4})
{3: 4}

如果我们希望完全覆盖,可以设置参数required

>>> schema = Schema({1: 2, 3: 4}, required=True)
>>> try:
...   schema({3: 4})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True

或者仅仅设置必须含有其中某一个键key

>>> schema = Schema({Required(1): 2, 3: 4})
>>> try:
...   schema({3: 4})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
>>> schema({1: 2})
{1: 2}

或者仅仅对某一个键设置可选择属性:

>>> from voluptuous import Optional
>>> schema = Schema({1: 2, Optional(3): 4}, required=True)
>>> try:
...   schema({})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "required key not provided @ data[1]"
True
>>> schema({1: 2})
{1: 2}
>>> try:
...   schema({1: 2, 4: 5})
...   raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
...   exc = e
>>> str(exc) == "extra keys not allowed @ data[4]"
True
>>> schema({1: 2, 3: 4})
{1: 2, 3: 4}

上一篇:Python数据验证库(二)validator
http://www.jianshu.com/p/eee56214af9c

    原文作者:kaley_ma
    原文地址: https://www.jianshu.com/p/0a5047a04ffd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞