gpt4 book ai didi

python - 如何自定义 Cerberus 的错误信息?

转载 作者:太空宇宙 更新时间:2023-11-03 14:48:31 25 4
gpt4 key购买 nike

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

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

最佳答案

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

>>> 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!']}

看看 source code获取可用的错误代码和模板变量。

关于python - 如何自定义 Cerberus 的错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com