按方案验证python字典。
dschema的Python项目详细描述
关于dschema
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)