Python:用于验证模式和自定义错误消息的jsonschema包
发布时间:2020-12-20 13:44:52 所属栏目:Python 来源:网络整理
导读:鉴于此架构: { "type": "object","properties": { "account": { "type": "object","required": ["id"],"properties": { "id": {"type": "number"} } },"name": {"type": "string"},"trigger": { "type": "object","required": ["type"],"properties": { "ty
鉴于此架构:
{ "type": "object","properties": { "account": { "type": "object","required": ["id"],"properties": { "id": {"type": "number"} } },"name": {"type": "string"},"trigger": { "type": "object","required": ["type"],"properties": { "type": {"type": "string"} } },"content": { "type": "object","properties": { "emails": { "type": "array","minItems": 1,"items": { "type": "object","required": ["fromEmail","subject"],"properties": { "fromEmail": {"type": "string","format": "email"},"subject": {"type": "string"} } } } } } } } 我正在尝试使用jsonschema.Draft4Validator来验证POSTed JSON对象以检查其有效性,但我在尝试从返回的错误中提出更好的人类可读消息时遇到了一些问题. 以下是我的验证方式: from jsonschema import Draft4Validator v = Draft4Validator(self.schema) errors = sorted(v.iter_errors(autoresponder_workflow),key=lambda e: e.path) if errors: print(','.join( '%s %s %s' % (error.path.popleft(),error.path.pop(),error.message) for error in errors )) 错误消息如下所示: 内容电子邮件[]太短,触发类型无类型为u’string’ 我试图创建一个看起来更像的错误消息请在您的工作流程中添加至少一封电子邮件,“”请确保您的所有电子邮件都包含主题行,“等 解决方法
您可以捕获
ValidationError exception并根据ValidationError元数据为特定情况构建自定义消息.在这个对象中你有:
验证失败的信息:其值和架构路径失败实例的信息:验证失败时的路径和值子模式中可能存在的错误原因(由非验证错误引起的错误) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |