Python:jsonschema程序包,用于验证架构和自定义错误消息

den*_*icz 6 python validation jsonschema

给定此架构:

{
    "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"}
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图用来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
    ))
Run Code Online (Sandbox Code Playgroud)

错误消息如下所示:

content emails [] is too short, trigger type None is not of type u'string'

我正在尝试创建看起来更像是请向您的工作流中添加至少一封电子邮件,“”请确保所有电子邮件都包含主题行“的错误消息,等等

小智 10

我需要在发生错误时向用户显示更详细的自定义消息。我通过向架构中的属性添加一个字段然后在 ValidationError 上查找它来做到这一点。

import json
import jsonschema


def validate(_data, _schema):
    try:
        jsonschema.validate(_data, _schema)
    except jsonschema.ValidationError as e:
        return e.schema["error_msg"] 


schema = {
    "title": "index",
    "type": "object",
    "required": [
        "author",
        "description"
    ],
    "properties": {
        "author": {
            "type": "string",
            "description": "Name of the Author",
            "minLength": 3,
            "default": "",
            "error_msg": "Please provide a Author name"
        },
        "description": {
            "type": "string",
            "description": "Short description",
            "minLength": 10,
            "default": "",
            "error_msg": "Please add a short description"
        }
    }
}

data = {
    "author": "Jerakin",
    "description": ""
}
Run Code Online (Sandbox Code Playgroud)


jru*_*ren 1

您可以捕获ValidationError 异常,并根据 ValidationError 元数据为您想要的特定情况构建自定义消息。在这个对象中你有:

失败的验证器的信息:其值和模式路径 失败的实例的信息:验证失败时的路径和值 子模式中可能出现的错误原因(由非验证错误引起的错误)