工作中需要对如下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, timedef 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 validateself.__validate_definitions(definitions, field)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 940, in __validate_definitionsresult = validate_rule(rule)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 922, in validate_rulereturn validator(definitions.get(rule, None), field, value)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 1234, in _validate_schemaself.__validate_schema_sequence(field, schema, value)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 1259, in __validate_schema_sequenceupdate=self.update, normalize=False)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 877, in validateself.__validate_definitions(definitions, field)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 940, in __validate_definitionsresult = validate_rule(rule)File "C:\Python27\lib\site-packages\cerberus\validator.py", line 921, in validate_rulevalidator = 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在构建的时候需要使用数组[]。

转载于:https://www.cnblogs.com/yanzibuaa/p/9110983.html

schema list validator --python cerberus相关推荐

  1. Python Cerberus

    cerberus地狱犬 (Cerberus是一个用于Python的轻量级且可扩展的数据验证库) 前言 文章内容有点多,是自己学习cerberus的记录,原文,由于篇幅有限,源码的解析就没有了,源码不是 ...

  2. python cerberus Validator参数校验

    最简单用法 # 最简单用法 from cerberus import Validator schema = {'name1': {'type': 'string'}, 'name2': {'type' ...

  3. Cerberus恶意软件团队解散,10万美元拍卖源代码工程

    Cerberus银行木马,是一款专门针对安卓系统的恶意软件,最早出现在2019年6月,在发现的时候安全人员认为他是Anubis恶意软件的变种. 但这个银行木马的团队却与其他编写恶意软件的团队不太一样. ...

  4. 【Python】Json Schema的使用【原创】

    Json Schema在Python中的应用 一. 背景 二.概述 三.介绍 四.Python中使用 五.例子 六.参考 一. 背景 之前在做容器发布系统的时候,在部署时需要对提交的deploymen ...

  5. python---(2)Python库资源大全

    转载地址:https://zhuanlan.zhihu.com/p/27350980 本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQu ...

  6. Python开发资源速查表

    Python开发资源速查表 Python实现算法和设计模式 algorithms - Python的一个算法模块. PyPattyrn - 一个用于实现常见设计模式的简单而有效的库. python-p ...

  7. python资源全汇总—中文版

    原始来源:https://github.com/vinta/awesome-python 真棒Python 管理面板 算法和设计模式 反垃圾邮件 资产管理 音频 验证 构建工具 缓存 ChatOps工 ...

  8. Life is short.,You need Python

    真棒Python  https://awesome-python.com/ 精选的Python框架,库,软件和资源的精选列表. 灵感来自awesome-php. 真棒Python 管理员面板 算法和设 ...

  9. Python资源汇总

    Python 目录: 管理面板 算法和设计模式 反垃圾邮件 资产管理 音频 验证 构建工具 缓存 ChatOps工具 CMS 代码分析和Linter 命令行工具 兼容性 计算机视觉 并发和并行性 组态 ...

最新文章

  1. 如何用Splunk建立可疑DNS报警系统
  2. Java基础之static关键字的用法
  3. 数据挖掘在呼叫中心的六大应用点
  4. poj 2182 Lost Cows 解题报告
  5. python常用包数据分析_数据分析领域常用的五个Python包
  6. ImportError: No module named ‘pandas.io.data‘
  7. python开发网络小工具_Python 实现简单网络应用程序开发
  8. Windows 两条命令找到占用你某个端口的程序
  9. 微信小程序背景图片如何设置--如何用background-image Base64设置背景
  10. Ueditor编辑器 .Net 版
  11. 语音信号处理(赵力)作业答案1-3章
  12. Android Dialog之间的层级设置(WindowManager.LayoutParams)
  13. FRP 内网穿透下载配置
  14. 关于用LaTeX写英文论文
  15. The Shawshank Redemption-1
  16. 视数字人民币为假想敌——数字美元的来龙去脉
  17. 技术分享 | 学做测试平台开发-Vuetify 框架
  18. AMM做市无常损失对冲分析系列(一)—— 损益及期权对冲模型构建
  19. win11设置任务栏不合并的方法教程
  20. linux下查看java 占用cpu使用情况

热门文章

  1. 当定频神器爱上多线程|ROS2定频话题发布Demo
  2. 贴片电容封装尺寸与常规的贴片电阻的标准封装及额定功率 (转)
  3. 拓扑结构和几何结构的区别
  4. 吴思里:PCG腾讯文档前端面试经历
  5. 使用示波器的正确姿势
  6. Oracle查询CLOB类型字段的内容:
  7. C# 2.0 泛型编程
  8. MACD多周期共振指标公式,日周月共振
  9. 指令周期 机器周期 状态周期 振荡时钟周期(时钟周期)
  10. Python之 【模型建立和测试-模型测试模板】