Created
January 21, 2019 06:49
-
-
Save shipengtaov/82b6a6e3321793882b5dc4a28f43bf39 to your computer and use it in GitHub Desktop.
customize error messages of Cerberus(https://github.com/pyeve/cerberus)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
https://stackoverflow.com/questions/47730454/how-can-i-customize-error-messages-of-cerberus | |
""" | |
import cerberus | |
class CustomErrorHandler(cerberus.errors.BasicErrorHandler): | |
messages = cerberus.errors.BasicErrorHandler.messages.copy() | |
messages[cerberus.errors.REQUIRED_FIELD.code] = '用户名为必填项' | |
messages[cerberus.errors.BAD_TYPE.code] = '用户名必须是字符串' | |
v = cerberus.Validator( | |
{ | |
'username': { | |
'required': True, | |
'type': 'string', | |
} | |
}, | |
error_handler=CustomErrorHandler | |
) | |
print(v.validate({})) | |
print(v.errors) | |
print(v.validate({'username': 1})) | |
print(v.errors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment