按方案验证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第三方库


热门话题
Javalog4j2。xml和log4j2test。eclipse中的xml   java映像未显示在surfaceview中   在Java中,能否在for之后立即放置if?   java调用构造函数的不同方式是什么?   java为什么不将其视为多重继承,而所有类都首先从对象类扩展,然后再扩展其他类   带有ms access的java不显示数据库结果   java Eclipse命令行URL参数切断https   java Android JNI回调似乎调用了一个随机方法   java Apache Camel处理XMLFile中声明的编码   java Bonita BPM不要等待Bonita的函数结束   布尔Java:构建逻辑表达式,然后验证它们   java在不使用QueryString的情况下将变量从一个网站页面传递到另一个网站页面   java ORA01861:文本与格式字符串不匹配   java字节[]字符串到C中的字符串#   java试图通过socket发送sqlite数据库文件   java如何使用命令行更改属性文件中的浏览器值以运行selenium测试用例