簡體   English   中英

如何自定義Cerberus的錯誤消息?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM