按方案验证python字典。

dschema的Python项目详细描述


关于dschema

pypiMaster Documentation Statuscodecov

dschema是一个小库,用于根据模式验证python字典对象的内容。

模式可以在代码中定义,也可以完全定义为文本(通常从json解析)

dschema主要用于验证用json编写的配置文件。

示例

有关更多示例,请参见文档链接

importreimportphonenumbersimportdschema# https://github.com/daviddrysdale/python-phonenumbers# pip install phonenumbersdefphone_type(number):# Exceptions are validation errors# Very similar design to the "argparse" modulereturnphonenumbers.parse(number)defssn_type(ssn):ifre.match('^\d{3}-?\d{2}-?\d{4}$',ssn):returnssnelse:raiseValueError('"{}" is not a valid SSN.')schema={'person':{'first_name':dschema.prop(required=True),'last_name':dschema.prop(required=True),'phone':dschema.prop(required=True,type=phone_type),'ssn':dschema.prop(required=True,type='ssn_type'),dschema.Required:True# "person" namespace is required, you must specify# even if "person" itself contains required properties},# Allow a raw dictionary value to pass through'other_info':dschema.prop(default=dict(),dict=True),# default to False if not present'subscribed':dschema.prop(default=False,type=bool)}validator=dschema.Validator(schema)# you can use this to add types that are recognized by name.# which is useful if you want your schema to be entirely textualvalidator.add_type('ssn_type',ssn_type)# you will need to define default types on your own# if you want to reference them by name# validator.add_type('int', int)data={'person':{'first_name':"John",'last_name':"Smith",'phone':'+1 234 5678 9000','ssn':'123-45-6789'},'other_info':{'website':'www.johnsmith.com',}}# If namespace is left False, a plain dictionary is returnedresult=validator.validate(data,namespace=True)print(result)# Prints: (un-indented)# Namespace(#     person=Namespace(#         first_name='John',#         last_name='Smith',#         phone=PhoneNumber(...),#         ssn='123-45-6789'),#     other_info={'website': 'www.johnsmith.com'},#     subscribed=False# )# Each Namespace is just a dynamic objectprint(result.person.first_name)# -> Johnprint(result.person.last_name)# -> Smithprint(result.person.phone)# - > Country Code: 1 National Number: 23456789000print(result.person.ssn)# -> 123-45-6789print(result.other_info)# -> {'website': 'www.johnsmith.com'}print(result.subscribed)# -> False (default)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java 401在API URL上带有声明性Http客户端,并带有@Secured(SecurityRule.IS_ANONYMOUS)注释   java如何在Android中创建计时器?   Java8WebStart安全弹出窗口   java会通过以下两种方式导致堆空间耗尽吗?   java项目调度GA:染色体的高效数据结构   java Apache POI:如何在Excel文件中插入列   java在JRE系统库中每个jar扮演什么角色   java如何在抽象类中执行@mock(不是注入mock)   java如何使用opensearch和Lucene发送搜索查询?   java在ApachePOI中处理空列   java广播接收器未接收到目标   java错误ELF类:ELF类64(可能原因:体系结构字宽不匹配)   java调用Web服务(SSL)时出错   用于iot集线器设备固件更新的java Rest API   通过xslt将xml转换为文本文件时引发java异常   Java linux打印问题   Java XML转换器重复行   java从另一个类的方法将数组导入mainActivity类   多线程选择与Java交互的线程   我想在java程序中打印以下格式的文件: