[英]How can I customize error messages of Cerberus?
我想本地化Cerberus返回的錯誤消息,例如我想實現以下內容:
>>> validator.schema = {'animal': {'forbidden': ['Einhorn']}}
>>> validator({'animal': 'Einhorn'})
False
>>> validator.errors
{'animal': ['VERBOTEN!']} # instead of 'unallowed value Einhorn'
您可以簡單地從cerberus.errors
模塊BasicErrorhandler
默認錯誤處理程序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!']}
查看可用錯誤代碼和模板變量的源代碼 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.