如何自定义 Cerberus 的错误消息?

fun*_*ure 3 python cerberus

我想本地化 Cerberus 返回的错误消息,例如我想实现以下目标:

>>> validator.schema = {'animal': {'forbidden': ['Einhorn']}}
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']}  # instead of 'unallowed value Einhorn'
Run Code Online (Sandbox Code Playgroud)

fun*_*ure 10

您可以简单地BasicErrorhandlercerberus.errors模块中继承默认错误处理程序,并根据需要调整消息模板:

>>> class CustomErrorHandler(errors.BasicErrorHandler):
...     messages = errors.BasicErrorHandler.messages.copy()
...     messages[errors.FORBIDDEN_VALUE.code] = 'VERBOTEN!'
...     
>>> validator = Validator(schema, error_handler=CustomErrorHandler)
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']}
Run Code Online (Sandbox Code Playgroud)

查看可用错误代码和模板变量的源代码