架构加载和验证库
schemable的Python项目详细描述
schemable是一个模式解析和验证库,让您可以简单地使用字典、列表、类型和可调用项定义模式。
链接
功能
- 使用dict、list和type对象的简单模式定义
- 使用Any、All、As和谓词的复杂模式定义
- 详细的验证错误消息
- 验证失败时部分数据加载
- 严格和非严格解析模式
- Python3.4+
快速启动
使用pip安装:
pip install schemable
使用dict和list对象定义架构:
fromschemableimportSchema,All,Any,As,Optional,SchemaErroruser_schema=Schema({'name':str,'email':All(str,lambdaemail:len(email)>3and'@'inemail),'active':bool,'settings':{Optional('theme'):str,Optional('language',default='en'):str,Optional('volume'):int,str:str},'aliases':[str],'phone':All(str,As(lambdaphone:''.join(filter(str.isdigit,phone))),lambdaphone:10<=len(phone)<=15),'addresses':[{'street_addr1':str,Optional('street_addr2',default=None):Any(str,None),'city':str,'state':str,'country':str,'zip_code':str}]})
然后通过将数据传递给user_schema():
# Fail!result=user_schema({'name':'Bob Smith','email':'bob.example.com','active':1,'settings':{'theme':False,'extra_setting1':'val1','extra_setting2':True},'phone':1234567890,'addresses':[{'street_addr1':'123 Lane','city':'City','state':'ST','country':'US','zip_code':11000}]})print(result)# SchemaResult(# data={'name': 'Bob Smith',# 'settings': {'extra_setting1': 'val1',# 'language': 'en'}# 'addresses': [{'street_addr1': '123 Lane',# 'city': 'City',# 'state': 'ST',# 'country': 'US',# 'street_addr2': None}]},# errors={'email': "bad value: <lambda>('bob.example.com') should evaluate to True",# 'active': 'bad value: type error, expected bool but found int',# 'settings': {'theme': 'bad value: type error, expected str but found bool',# 'extra_setting2': 'bad value: type error, expected str but found bool'},# 'phone': 'bad value: type error, expected str but found int',# 'addresses': {0: {'zip_code': 'bad value: type error, expected str but found int'}},# 'aliases': 'missing required key'})# Fail!result=user_schema({'name':'Bob Smith','email':'bob@example.com','active':True,'settings':{'theme':False,'extra_setting1':'val1','extra_setting2':'val2'},'phone':'123-456-789','addresses':[{'street_addr1':'123 Lane','city':'City','state':'ST','country':'US','zip_code':'11000'}]})print(result)# SchemaResult(# data={'name': 'Bob Smith',# 'email': 'bob@example.com',# 'active': True,# 'settings': {'extra_setting1': 'val1',# 'extra_setting2': 'val2',# 'language': 'en'},# 'addresses': [{'street_addr1': '123 Lane',# 'city': 'City',# 'state': 'ST',# 'country': 'US',# 'zip_code': '11000',# 'street_addr2': None}]},# errors={'settings': {'theme': 'bad value: type error, expected str but found bool'},# 'phone': "bad value: <lambda>('123456789') should evaluate to True",# 'aliases': 'missing required key'})
或者在验证失败时引发异常,而不是返回结果:
# Fail strictly!try:user_schema({'name':'Bob Smith','email':'bob@example.com','active':True,'settings':{'theme':False,'extra_setting1':'val1','extra_setting2':'val2'},'phone':'123-456-789','addresses':[{'street_addr1':'123 Lane','city':'City','state':'ST','country':'US','zip_code':'11000'}]},strict=True)exceptSchemaErrorasexc:print(exc)# Schema validation failed: \# {'settings': {'theme': 'bad value: type error, expected str but found bool'}, \# 'phone': "bad value: <lambda>('123456789') should evaluate to True", \# 'aliases': 'missing required key'}
成功验证后访问分析的数据:
# Pass!result=user_schema({'name':'Bob Smith','email':'bob@example.com','active':True,'settings':{'theme':'dark','extra_setting1':'val1','extra_setting2':'val2'},'phone':'123-456-7890','aliases':[],'addresses':[{'street_addr1':'123 Lane','city':'City','state':'ST','country':'US','zip_code':'11000'}]})print(result)# SchemaResult(# data={'name': 'Bob Smith',# 'email': 'bob@example.com',# 'active': True,# 'settings': {'theme': 'dark',# 'extra_setting1': 'val1',# 'extra_setting2': 'val2',# 'language': 'en'},# 'phone': '1234567890',# 'aliases': [],# 'addresses': [{'street_addr1': '123 Lane',# 'city': 'City',# 'state': 'ST',# 'country': 'US',# 'zip_code': '11000',# 'street_addr2': None}]},# errors={})
有关详细信息,请参阅https://schemable.readthedocs.io上的完整文档。
更改日志
v0.5.0(2018-08-17)
- 如果嵌套架构是用strict=True(例如Schema({'key':Schema({...},strict=True)}))创建的,则不要从该架构加载部分数据。
V0.4.1(2018-08-14)
- 修复以前的修复方法,其中架构结果可以有data或errors,架构类作为键。
- 如果在源数据中找不到'key',请确保Select('key', <iteratee>)不会调用<iteratee>。
v0.4.0(2018-08-14)
- 修复使用Optional(key)的架构对象将导致SchemaResult.errors[Optional(key)]的情况。请确保设置了SchemaResult.errors[key]。
- 当源对象中不存在'other_key'时,使用Schema({'key':Select('other_key')})时忽略KeyError。而是返回一个丢失的密钥错误。
V0.3.1(2018-07-31)
- 如果validate callable引发异常,请将其字符串表示形式用作架构错误消息。以前,当验证器返回false并引发异常时,会使用一条自定义错误消息,指出Callable的计算结果应为true。该消息现在只在验证器不发出但返回错误时返回。
v0.3.0(2018-07-27)
- 添加架构帮助程序:
- Select
- Use
- 在由As返回的错误消息中包含execption类名。
- 在从字典模式解析时,始终返回dict,而不是尝试将源数据的类型用作初始值设定项。(breaking change)
V0.2.0(2018-07-25)
- 将Collection重命名为List。(breaking change)
- 将Object重命名为Dict。(breaking change)
- 允许collections.abc.Mapping对象是有效的Dict对象。
- 修改Type验证,以便只将对象与isinstance进行比较。
- 改进文档。
v0.1.0(2018-07-24)
- 第一次释放。
许可证
麻省理工学院许可证(MIT)
版权所有(c)2018,德里克·吉兰
兹免费准许任何人取得副本 本软件和相关文档文件(“软件”)的 在软件中不受限制,包括但不限于 使用、复制、修改、合并、发布、分发、再授权和/或出售 软件的副本,并允许软件的用户 在满足以下条件的情况下,可以这样做:
上述版权公告及本许可公告须包括在 软件的拷贝或大部分。
本软件按“原样”提供,无任何形式的保证,明示或 进口撒谎,包括但不限于适销性保证, 适合某一特定目的和非侵犯性。在任何情况下 作者或版权所有者应对任何索赔、损害或其他 责任,无论是在诉讼或合同中,侵权行为或其他,产生于, 不属于或与本软件有关,或使用或与本软件的其他交易有关。 软件。