Python格式验证库 Cerberus

作者 MrStranger 关注

2016.08.02 14:44 字数 2140 阅读 79评论 0喜欢 1

Cerberus是一个验证Python对象、MongoDB格式的库,

安装(稳定版本)

http://docs.python-cerberus.org/en/stable/install.html

pip install cerberus

基本用法

1⃣️定义基本格式
2⃣️生成Validator类的实例v
3⃣️定义要验证的dictionary(Python字典)
4⃣️实例v调用validator()函数(返回boolean值)

>>> schema = {'name': {'type': 'string'}}
>>> v = Validator(schema) >>> document = {'name': 'john doe'}
>>> v.validate(document)
True

也可以这样:

>>> v = Validator()
>>> v.validate(document, schema)
True

在version 0.4.1之后,可以这样:

>>> document = {'name': 'john doe'}
>>> v(document)
True

Validator执行时不会抛出异常或因为异常发生而停止运行,整个函数会执行完毕。也就是说验证成功就返回true,否则返回false。可以通过调用errors()函数来获取相关的信息。

>>> schema = {'name': {'type': 'string'}, 'age': {'type': 'integer', 'min': 10}}
>>> document = {'name': 1337, 'age': 5}
>>> v.validate(document, schema)
False
>>> v.errors
{'age': 'min value is 10', 'name': 'must be of string type'}

验证规则(验证语法中的一些参数规范):

type:

type可有以下取值:

* string
* integer
* float
* number (integer or float)
* boolean
* datetime
* dict (formally collections.mapping)
* list (formally collections.sequence, excluding strings)
* set

可以定义多个取值范围

>>> v = Validator({'quotes': {'type': ['string', 'list']}})
>>> v.validate({'quotes': 'Hello world!'})
True
>>> v.validate({'quotes': ['Do not disturb my circles!', 'Heureka!']})
True
>>> v = Validator({'quotes': {'type': ['string', 'list'], 'schema': {'type': 'string'}}})
>>> v.validate({'quotes': 'Hello world!'})
True
>>> v.validate({'quotes': [1, 'Heureka!']})
False
>>> v.errors
{'quotes': {0: 'must be of string type'}}

required:

1⃣️如果设置了'required': True那么这个键值对是必须的,如果没有,那么将返回false
2⃣️可在validate()函数调用时设置update=True,来忽略require规则
3⃣️对于string类型的规定,“”空字符串符合required规则

>>> schema = {'name': {'required': True, 'type': 'string'}, 'age': {'type': 'integer'}}
>>> v = Validator(schema)
>>> document = {'age': 10}
>>> v.validate(document)
False
>>> v.errors
{'name': 'must be of string type'} >>> v.validate(document, update=True)
True

readonly:

nullable:

设置为true,则值可有两种属性 (**和None)

>>> schema = {'a_nullable_integer': {'nullable': True, 'type': 'integer'}, 'an_integer': {'type': 'integer'}}
>>> v = Validator(schema) >>> v.validate({'a_nullable_integer': 3})
True
>>> v.validate({'a_nullable_integer': None})
True >>> v.validate({'an_integer': 3})
True
>>> v.validate({'an_integer': None})
False
>>> v.errors
{'an_integer': 'must be of integer type'}

minlength, maxlength:

只针对于string和list

>>> schema = {'name': {'type': 'string', 'maxlength': 10}}

min, max:

integer,float和number

>>> schema = {'name': {'type': 'string'}, 'age': {'type': 'integer', 'min': 10}}
>>> document = {'name': 1337, 'age': 5}
>>> v.validate(document, schema)
False
>>> v.errors
{'age': 'min value is 10', 'name': 'must be of string type'}

allowed:

string , list and int
规定取值范围:

>>> schema = {'role': {'type': 'list', 'allowed': ['agent', 'client', 'supplier']}}
>>> v = Validator(schema)
>>> v.validate({'role': ['agent', 'supplier']})
True >>> v.validate({'role': ['intern']})
False
>>> v.errors
{'role': "unallowed values ['intern']"} >>> schema = {'role': {'type': 'string', 'allowed': ['agent', 'client', 'supplier']}}
>>> v = Validator(schema)
>>> v.validate({'role': 'supplier'})
True >>> v.validate({'role': 'intern'})
False
>>> v.errors
{'role': 'unallowed value intern'} >>> schema = {'a_restricted_integer': {'type': 'integer', 'allowed': [-1, 0, 1]}}
>>> v = Validator(schema)
>>> v.validate({'a_restricted_integer': -1})
True >>> v.validate({'a_restricted_integer': 2})
False
>>> v.errors
{'a_restricted_unteger': 'unallowed value 2'}

empty:

只适用于string
默认为true(字符串可为“”)

>>> schema = {'name': {'type': 'string', 'empty': False}}
>>> document = {'name': ''}
>>> v.validate(document, schema)
False >>> v.errors
{'name': 'empty values not allowed'}

schema (dict):

字典dict内的键值对规则 (子规则)

>>> schema = {'a_dict': {'type': 'dict', 'schema': {'address': {'type': 'string'}, 'city': {'type': 'string', 'required': True}}}}
>>> document = {'a_dict': {'address': 'my address', 'city': 'my town'}}
>>> v.validate(document, schema)
True

schema (list):

列表list内的键值对规则 (子规则)

>>> schema = {'a_list': {'type': 'list', 'schema': {'type': 'integer'}}}
>>> document = {'a_list': [3, 4, 5]}
>>> v.validate(document, schema)
True

valueschema:

规定了dict内所有值的规则?

>>> schema = {'numbers': {'type': 'dict', 'valueschema': {'type': 'integer', min: 10}}}
>>> document = {'numbers': {'an integer': 10, 'another integer': 100}}
>>> v.validate(document, schema)
True >>> document = {'numbers': {'an integer': 9}}
>>> v.validate(document, schema)
False >>> v.errors
{'numbers': {'an integer': 'min value is 10'}}

propertyschema:

>>> schema = 'a_dict': {'type': 'dict', 'propertyschema': {'type': 'string', 'regex': '[a-z]+'}}
>>> document = {'a_dict': {'key': 'value'}}
>>> v.validate(document, schema)
True >>> document = {'a_dict': {'KEY': 'value'}}
>>> v.validate(document, schema)
False

regex:

正则表达式

>>> schema = {'email': {'type': 'string', 'regex': '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}}
>>> document = {'email': 'john@example.com'}
>>> v.validate(document, schema)
True >>> document = {'email': 'john_at_example_dot_com'}
>>> v.validate(document, schema)
False >>> v.errors
{'email': 'value does not match regex "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"}

dependencies:

依赖链

>>> schema = {'field1': {'required': False}, 'field2': {'required': False, 'dependencies': ['field1']}}
>>> document = {'field1': 7}
>>> v.validate(document, schema)
True >>> document = {'field2': 7}
>>> v.validate(document, schema)
False >>> v.errors
{'field2': 'field "field1" is required'} >>> schema = {'field1': {'required': False}, 'field2': {'required': True, 'dependencies': {'field1': ['one', 'two']}}}
>>> document = {'field1': 'one', 'field2': 7}
>>> v.validate(document, schema)
True >>> document = {'field1': 'three', 'field2': 7}
False >>> v.errors
{'field2': "field 'field1' is required with values: ['one', 'two']"} >>> # same as using a dependencies list
>>> document = {'field2': 7}
>>> v.validate(document, schema)
{'field2': "field 'field1' is required"} >>> # one can also pass a single dependency value
>>> schema = {'field1': {'required': False}, 'field2': {'dependencies': {'field1': 'one'}}}
>>> document = {'field1': 'one', 'field2': 7}
>>> v.validate(document, schema)
True >>> document = {'field1': 'two', 'field2': 7}
False >>> v.errors
{'field2': "field 'field1' is required with values: one"}

anyof、allof、noneof、oneof

>>> schema = {'prop1':
... {'type': 'number',
... 'anyof':
... [{'min': 0, 'max': 10}, {'min': 100, 'max': 110}]}}
>>> doc = {'prop1': 5}
>>> v.validate(document, schema)
True
>>> doc = {'prop1': 105}
>>> v.validate(document, schema)
True
>>> doc = {'prop1': 55}
>>> v.validate(document, schema)
False
>>> print v.errors
{'prop1': {'anyof': 'no definitions validated', 'definition 1': 'min value is 100', 'definition 0': 'max value is 10'}}

Allowing the Unknown:

>>> schema = {'name': {'type': 'string', 'maxlength': 10}}
>>> v.validate({'name': 'john', 'sex': 'M'})
False
>>> v.errors
{'sex': 'unknown field'}
>>> v = Validator(schema={})
>>> v.allow_unknown = True
>>> v.validate({'name': 'john', 'sex': 'M'})
True >>> v = Validator(schema={})
>>> v.allow_unknown = {'type': 'string'}
>>> v.validate({'an_unknown_field': 'john'})
True
>>> v.validate({'an_unknown_field': 1})
False
>>> v.errors
{'an_unknown_field': 'must be of string type'} >>> v = Validator(schema=schema, allow_unknown=True)
>>> v.validate({'name': 'john', 'sex': 'M'})
True >>> # by default allow_unknown is False for the whole document.
>>> v = Validator()
>>> v.allow_unknown
False >>> # we can switch it on (or set it to a validation schema) for individual subdocuments
>>> schema = {
... 'name': {'type': 'string'},
... 'a_dict': {
... 'type': 'dict',
... 'allow_unknown': True,
... 'schema': {
... 'address': {'type': 'string'}
... }
... }
... } >>> v.validate({'name': 'john', 'a_dict':{'an_unknown_field': 'is allowed'}}, schema)
True >>> # this fails as allow_unknown is still False for the parent document.
>>> v.validate({'name': 'john', 'an_unknown_field': 'is not allowed', 'a_dict':{'an_unknown_field': 'is allowed'}}, schema)
False >>> v.errors
{'an_unknown_field': 'unknown field'}

Type Coercion:

回调函数的值代替原值

>>> v = Validator({'amount': {'type': 'integer'}})
>>> v.validate({'amount': '1'})
False >>> v = Validator({'amount': {'type': 'integer', 'coerce': int}})
>>> v.validate({'amount': '1'})
True
>>> v.document
{'amount': 1} >>> to_bool = lambda v: v.lower() in ['true', '1']
>>> v = Validator({'flag': {'type': 'boolean', 'coerce': to_bool}})
>>> v.validate({'flag': 'true'})
True
>>> v.document
{'flag': True}

Validated Method:

v = Validator(schema)
valid_documents = [x for x in [v.validated(y) for y in documents] if x is not None]

Vanilla Python:

>>> import yaml
>>> schema_text = '''
...name:
... type: string
...age':
... type: integer
... min: 10
...'''
>>> schema = yaml.load(schema_text)
>>> document = {'name': 1337, 'age': 5}
>>> v.validate(document, schema)
False
>>> v.errors
{'age': 'min value is 10', 'name': 'must be of string type'} 参考来源:http://www.jianshu.com/p/ca852f679fcc
http://docs.python-cerberus.org/en/stable/index.html

Python 服务器端表单验证插件的更多相关文章

  1. jQuery学习之:Validation表单验证插件

    http://polaris.blog.51cto.com/1146394/258781/ 最近由于公司决定使用AJAX + Struts2来重构项目,让我仔细研究一下这两个,然后集中给同事讲讲,让每 ...

  2. (转)强大的JQuery表单验证插件 FormValidator使用介绍

    jQuery formValidator表单验证插件是客户端表单验证插件.在做B/S开发的时候,我们经常涉及到很多表单验证,例如新用户注册,填写个人资料,录入一些常规数据等等.在这之前,页面开发者(J ...

  3. 强大的JQuery表单验证插件 FormValidator使用介绍

    jQuery formValidator表单验证插件是客户端表单验证插件. 在做B/S开发的时候,我们经常涉及到很多表单验证,例如新用户注册,填写个人资料,录入一些常规数据等等.在这之前,页面开发者( ...

  4. 10个强大的Javascript表单验证插件推荐

    创建一个JavaScript表单验证插件,可以说是一个繁琐的过程,涉及到初期设计.开发与测试等等环节.实际上一个优秀的程序员不仅是技术高手,也应该是善假于外物的.本文介绍了10个不错的JavaScri ...

  5. nice-validator表单验证插件的简单使用

    前言 前端表单校验是过滤无效数据.假数据.有毒数据的第一步,是数据安全的第一道关卡,虽然我们不能100%相信客户端提交的数据(真正的校验还得在服务端进行),但设置前端表单校验也是至关重要的,自己写逻辑 ...

  6. nice-validator表单验证插件

    nice-validator表单验证插件的简单使用 前言 前端表单校验是过滤无效数据.假数据.有毒数据的第一步,是数据安全的第一道关卡,虽然我们不能100%相信客户端提交的数据(真正的校验还得在服务端 ...

  7. jquery validate表单验证插件-推荐

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

  8. 表单验证插件之jquery.validate.js

    提到表单验证的插件,第一个想到的就是jquery.validate.js,所以小生想在这里稍微详细地说一下这款插件的具体使用方法,便于理解,我直接附上整段demo的代码(没怎么调样式,主要是看js): ...

  9. jquery validate表单验证插件

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

随机推荐

  1. 【读书笔记 - Effective Java】01. 考虑用静态工厂方法代替构造器

    获取类的实例有两种方法: 1. 提供一个公有的构造器(最常用). 2. 提供一个公有的静态工厂方法(static factory method). // 静态工厂方法示例 public static ...

  2. QQ空间|qq人气号怎么赚钱?

    回报,付出的终极诉求,咱不论情怀. 在<怎么做一个QQ人气号>中,笔者大致提及,打造人气空间的流程,这里简单剖析下QQ人气空间的盈利模式. 关键词:转让,出售,广告,微商,合作,网红,接推 ...

  3. 初学者:__init__.py文件的作用

    __init__.py 文件的作用及意义 __init__.py文件是一个包必须的文件,即使它是空的,但也是必须的,如果没有这个文件,python将不会把该文件夹当做一个package,而仅仅是一个d ...

  4. python和java,php,c,c#,c++的对比

    1.C语言,它既有高级语言的特点,又具有汇编语言的特点,它是结构式语言.C语言应用指针:可以直接进行靠近硬件的操作,但是C的指针操作不做保护,也给它带来了很多不安全的因素.C++在这方面做了改进,在保 ...

  5. Python之函数装饰器

    在实际中,我们可能需要在不改变函数源代码和调用方式的情况下,为函数添加一些新的附加功能,能够实现这种功能的函数我们将其称之为装饰器.装饰器本质上其实还是是一个函数,用来装饰其它函数,为函数添加一些附加 ...

  6. Java Dictionary 类

    Dictionary 类是一个抽象类,用来存储键/值对,作用和Map类相似. 给出键和值,你就可以将值存储在Dictionary对象中.一旦该值被存储,就可以通过它的键来获取它.所以和Map一样, D ...

  7. day 4 集合

    1.集合 In [1]: a = (11,22,33,11,22,33) In [2]: a Out[2]: (11, 22, 33, 11, 22, 33) #元组 In [3]: b = [11, ...

  8. 屏蔽Drupal中的“Notice: Undefined index”警告

    原因:drupal默认使用E_ALL,即输出所有错误和警告.我们只需要修改错误显示级别即可. 方法: 1. 打开\sites\default\settings.php 追加一行 ini_set('er ...

  9. WebService-CXF使用

    一.SOAP和WSDL概念: SOAP(Simple Object Access Protocol):简单对象访问协议 SOAP作为一个基于XML语言的协议用于在网上传输数据 SOAP=在Http的基 ...

  10. Process Monitor工具找网吧广告

    很多网吧经常有遇到有一些客户机多了一些广告或者是可能是有中毒的情况.Process Monitor 软件可以方便的监视和记录系统各程序的进程线程,注册表,网络,文件读写等活动. 1,开超级用户,双击打 ...