cerberus

Python Cerberus: multipe schemas for a single filed?

自作多情 提交于 2019-12-07 22:44:48
问题 I am trying to use Cerberus to validate some data but I run into a problem. I defined several smaller schema such as: A = {"type": "dict", "required": False, "schema": {"name": {"type": "string"}}} B = {"type": "dict", "required": False, "schema": {"age": {"type": "integer"}}} C = {"type": "dict", "required": False, "schema": {"gender": {"type": "string"}}} And the higher level schema is like: {"something": {"type": "list", "schema": "type": [A, B, C]}} This obviously doesn't work. I want to

How can I customize error messages of Cerberus?

旧城冷巷雨未停 提交于 2019-12-06 07:23:26
问题 I want to localize the error messages Cerberus returns, e.g. I'd like to achieve the following: >>> validator.schema = {'animal': {'forbidden': ['Einhorn']}} >>> validator({'animal': 'Einhorn'}) False >>> validator.errors {'animal': ['VERBOTEN!']} # instead of 'unallowed value Einhorn' 回答1: You can simply subclass the default error handler BasicErrorhandler from the cerberus.errors module and adjust the message templates as you like: >>> class CustomErrorHandler(errors.BasicErrorHandler): ...

How can I customize error messages of Cerberus?

拥有回忆 提交于 2019-12-04 15:42:18
I want to localize the error messages Cerberus returns, e.g. I'd like to achieve the following: >>> validator.schema = {'animal': {'forbidden': ['Einhorn']}} >>> validator({'animal': 'Einhorn'}) False >>> validator.errors {'animal': ['VERBOTEN!']} # instead of 'unallowed value Einhorn' You can simply subclass the default error handler BasicErrorhandler from the cerberus.errors module and adjust the message templates as you like: >>> class CustomErrorHandler(errors.BasicErrorHandler): ... messages = errors.BasicErrorHandler.messages.copy() ... messages[errors.FORBIDDEN_VALUE.code] = 'VERBOTEN!'

Validating that two params have same amount elements using Cerberus

↘锁芯ラ 提交于 2019-12-01 11:54:27
Is there a way to have Cerberus validate that two fields have the same amount of elements? For instance, this document would validate: {'a': [1, 2, 3], b: [4, 5, 6]} And this won't: {'a': [1, 2, 3], 'b': [7, 8]} So far I have come up with this schema: {'a': {'required':False, 'type'= 'list', 'dependencies':'b'}, 'b': {'required':False, 'type'= 'list', 'dependencies':'a'}} But there's no rule to test the equal length of two fields. With a custom rule it is pretty straight-forward: >>> from cerberus import Validator >>> class MyValidator(Validator): def _validate_match_length(self, other, field,