schema list validator --python cerberus
工作中需要对如下json结构进行验证:
"ActiveStatus" : [
{
"effectiveDates" : {
"effectiveFrom" : "2018-05-10T12:44:17Z",
"effectiveTo" : "2018-05-11T00:29:29Z"
},
"status" : "Active",
"reason" : ""
},
{
"effectiveDates" : {
"effectiveFrom" : "2018-05-11T00:29:29Z"
},
"status" : "Inactive",
"reason" : "Expired/Matured"
}
],
使用cerberus, 定位到schema list.
(一)先从单条记录开始测试(cerberus_test_single.py)
from cerberus import Validator
from datetime import datetime, date, time def string_toDatetime(string):
return datetime.strptime(string, "%Y-%m-%d") schema={
'effectiveDates':{
'type':'dict',
'schema':{
'effectiveFrom':{'type':'datetime'},
'effectiveTo':{'type':'datetime'}
}
},
'status':{'type':'string','allowed':['Active','Inactive']},
'reason':{'type':'string'}
} document={
'effectiveDates':{
'effectiveFrom':string_toDatetime('2018-05-10'),
'effectiveTo':string_toDatetime('2018-05-11'),
},
'status':'Active',
'reason':'Expired'
} v=Validator(schema)
v.validate(document) print(v.errors)
在命令行运行文件,验证成功:
E:\Learning\AWS\cerberus>cerberus_test.py
{}
注:结果为{}表示v.errors中没有错误,即验证成功。
如果修改上述文件中的document为如下:
document={
'effectiveDates':{
'effectiveFrom':string_toDatetime('2018-05-10'),
'effectiveTo':string_toDatetime('2018-05-11'),
},
'status':'ctive',
'reason':'Expired'
}
此时将验证失败:
E:\Learning\AWS\cerberus>cerberus_test_single.py
{'status': ['unallowed value ctive']}
(二)加入list, 验证多条的情况:
首先想到将上述schema(红色部分)嵌套到一个schema里,然后type指定list:
schema={
'type':'list'
schema={
'effectiveDates':{
'type':'dict',
'schema':{
'effectiveFrom':{'type':'datetime'},
'effectiveTo':{'type':'datetime'}
}
},
'status':{'type':'string','allowed':['Active','Inactive']},
'reason':{'type':'string'}
}
}
代码如下(cerberus_test.py)
from cerberus import Validator
from datetime import datetime, date, time def string_toDatetime(string):
return datetime.strptime(string, '%Y-%m-%d') schema={
'activeStatus':{
'type':'list',
'schema':{
'effectiveDates':{
'type':'dict',
'schema':{
'effectiveFrom':{'type':'datetime'},
'effectiveTo':{'type':'datetime'}
}
},
'status':{'type':'string','allowed':['Active','Inactive']},
'reason':{'type':'string','allowed':['Expired','Matured']}
}
}
} document={
'activeStatus':[
{
'effectiveDates':{
'effectiveFrom':string_toDatetime('2018-05-10'),
'effectiveTo':string_toDatetime('2018-05-11')
},
'status':'Active',
'reason':'Expired'
},
{
'effectiveDates' : {
'effectiveFrom' :string_toDatetime('2018-05-11')
},
'status' : 'Inactive',
'reason' : 'Matured'
}
]
}
v=Validator(schema)
v.validate(document) print(v.errors)
命令行运行代码发现:
E:\Learning\AWS\cerberus>cerberus_test.py
Traceback (most recent call last):
File "E:\Learning\AWS\cerberus\test.py", line 48, in <module>
v.validate(document)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 877, in validate
self.__validate_definitions(definitions, field)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 940, in __validate_definitions
result = validate_rule(rule)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 922, in validate_rule
return validator(definitions.get(rule, None), field, value)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 1234, in _validate_schema
self.__validate_schema_sequence(field, schema, value)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 1259, in __validate_schema_sequence
update=self.update, normalize=False)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 877, in validate
self.__validate_definitions(definitions, field)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 940, in __validate_definitions
result = validate_rule(rule)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 921, in validate_rule
validator = self.__get_rule_handler('validate', rule)
File "C:\Python27\lib\site-packages\cerberus\validator.py", line 338, in __get_rule_handler
"domain.".format(rule, domain))
RuntimeError: There's no handler for 'status' in the 'validate' domain.
(三)解决办法:
仔细查看cerberus自带例子(http://docs.python-cerberus.org/en/stable/validation-rules.html#schema-list)
>>> schema = {'rows': {'type': 'list',
... 'schema': {'type': 'dict', 'schema': {'sku': {'type': 'string'},
... 'price': {'type': 'integer'}}}}}
>>> document = {'rows': [{'sku': 'KT123', 'price': 100}]}
>>> v.validate(document, schema)
True
发现它把schema又嵌入到一个shema里,而不是我想的那样,于是我这么做:
schema={
'activeStatus':{
'type':'list',
'schema':{
'schema':{
'effectiveDates':{
'type':'dict',
'schema':{
'effectiveFrom':{'type':'datetime'},
'effectiveTo':{'type':'datetime'}
}
},
'status':{'type':'string','allowed':['Active','Inactive']},
'reason':{'type':'string','allowed':['Expired','Matured']}
}
}
}
}
竟然可以成功验证!以下为完整的python文件(cerberus_test.py):
from cerberus import Validator
from datetime import datetime, date, time
#import pdb def string_toDatetime(string):
return datetime.strptime(string, '%Y-%m-%d') schema={
'activeStatus':{
'type':'list',
'schema':{
'schema':{
'effectiveDates':{
'type':'dict',
'schema':{
'effectiveFrom':{'type':'datetime'},
'effectiveTo':{'type':'datetime'}
}
},
'status':{'type':'string','allowed':['Active','Inactive']},
'reason':{'type':'string','allowed':['Expired','Matured']}
}
}
}
} document={
'activeStatus':[
{
'effectiveDates':{
'effectiveFrom':string_toDatetime('2018-05-10'),
'effectiveTo':string_toDatetime('2018-05-11')
},
'status':'Active',
'reason':'Expired'
},
{
'effectiveDates' : {
'effectiveFrom' :string_toDatetime('2018-05-11')
},
'status' : 'Inactive',
'reason' : 'Matured'
}
]
} #pdb.set_trace()
v=Validator(schema)
v.validate(document) print(v.errors)
注意:因为schema是list,document在构建的时候需要使用数组[]。
schema list validator --python cerberus的更多相关文章
- Json schema 以及在python中的jsonschema
目录 1. JSON Schema简介 2. JSON Schema关键字详解 2.1 $schema 2.2 title和description 2.3 type 3 type常见取值 3.1 当t ...
- Awesome Python
Awesome Python A curated list of awesome Python frameworks, libraries, software and resources. Insp ...
- Python资源汇总
Python 目录: 管理面板 算法和设计模式 反垃圾邮件 资产管理 音频 验证 构建工具 缓存 ChatOps工具 CMS 代码分析和Linter 命令行工具 兼容性 计算机视觉 并发和并行性 组态 ...
- Python库资源大全
转载地址:https://zhuanlan.zhihu.com/p/27350980 本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQu ...
- Life is short.,You need Python
真棒Python https://awesome-python.com/ 精选的Python框架,库,软件和资源的精选列表. 灵感来自awesome-php. 真棒Python 管理员面板 算法和设 ...
- python RESTful API框架:Eve 高速入门
Eve是一款Python的REST API框架.用于公布高可定制的.全功能的RESTful的Web服务.帮你轻松创建和部署API,本文翻译自Eve官方站点: http://python-eve.org ...
- Python库资源大全【收藏】
本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQuant整理加工而成,欢迎扩散.欢迎补充! 对机器学习.深度学习在量化投资中应用感兴趣的 ...
- Java使用Schema模式对XML验证
XML允许创作者定义自己的标签,因其灵活的特性让其难以编写和解析.因此必须使用某种模式来约束其结构.目前最流行的这种模式有两种:DTD和SCHEMA,而后者以其独特的优势即将取代DTD模式,目前只是过 ...
- [SoapUI]怎样运用Schema通过*.xsd文件来验证response对应的xml文件
添加Groovy Script脚本对Test Step进行验证 脚本如下(已经运行通过): import javax.xml.XMLConstants import javax.xml.transfo ...
随机推荐
- thinkphp5.0中英文切换
首先来看下它的配置: // 是否开启多语言 'lang_switch_on' => true, //语音列表 'lang_list' => ['zh-cn','en-us'], // 获取 ...
- GIAC2019 演讲精选 | 面向未来的黑科技——UI2CODE闲鱼基于图片生成跨端代码
一直以来, 如何从‘视觉稿’精确的还原出 对应的UI侧代码 一直是端侧开发同学工作里消耗比较大的部分,一方面这部分的工作 比较确定缺少技术深度,另一方面视觉设计师也需要投入大量的走查时间,有大量无谓的 ...
- [***]沙雕低错集(算起来因为低错挂掉的分快够我AK三场了……)
由于沙雕错太多了所以不想写了,看着就难受…… 各种沙雕错(自从上次考试开始各种犯沙雕低错……): !!!sort是不稳定的排序,如果排序结构题只按其中一个关键字排序,那么在关键字相等时,排序多次的结果 ...
- 基于opencv的RandomForest随机森林
2.OpenCV函数使用 OpenCV提供了随机森林的相关类和函数.具体使用方法如下: (1)首先利用CvRTParams定义自己的参数,其格式如下 CvRTParams::CvRTParams(in ...
- TreeSet之用外部比较器实现自定义有序(重要)
Student.java package com.sxt.set5; public class Student{ private String name; private int age; priva ...
- jQuery 链
通过 jQuery,可以把动作/方法链接在一起. Chaining 允许我们在一条语句中运行多个 jQuery 方法(在相同的元素上). jQuery 方法链接 直到现在,我们都是一次写一条 jQue ...
- PMC亮相IDF展示12G SAS分层存储解决方式
引领大数据连接.传送以及存储,提供创新半导体及软件解决方式的PMC公司(纳斯达克代码:PMCS)出席了2014年4月2-3日在深圳举办的2014 IDF英特尔开发人员论坛. 此次,PMC将在 1层展示 ...
- linux扫盲之CPU模式
相信研究linux的大大都知道linux有实模式.保护模式.虚拟模式三种. 不多说,拷贝黏贴! 80386开始,cpu有三种工作方式:实模式,保护模式和虚拟8086模式.只有在刚刚启动的时候是rea ...
- X-WAF 安装配置指南
X-WAF 是一款方便易用的云WAF,使用反向代理的方式介入Web服务器和访问者之间,不需要像 modSecurity 和 Naxsin 那样作为nginx的模块,需要进行编译安装 X-WAF使用 O ...
- win10 + 独显 + Anaconda3 + tensorflow_gpu1.13 安装教程(跑bert模型)
这里面有很多坑,最大的坑是发现各方面都装好了结果报错 Loaded runtime CuDNN library: 7.3.1 but source was compiled with: 7.4.1, ...