3

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

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

1 回答 1

10

BasicErrorhandler您可以简单地从模块中继承默认错误处理程序cerberus.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!']}

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

于 2017-12-09T16:07:56.513 回答