Skip to content

Instantly share code, notes, and snippets.

@shipengtaov
Created January 21, 2019 06:49
Show Gist options
  • Save shipengtaov/82b6a6e3321793882b5dc4a28f43bf39 to your computer and use it in GitHub Desktop.
Save shipengtaov/82b6a6e3321793882b5dc4a28f43bf39 to your computer and use it in GitHub Desktop.
customize error messages of Cerberus(https://github.com/pyeve/cerberus)
"""
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