View difference between Paste ID: L9m3ZD8e and fkhZvBGr
SHOW: | | - or go back to the newest paste.
1
2
DAWLOD HERE : http://fitness-assist.com/ran?r=5YCu
3
4
import copy
5
import cerberus
6
from cerberus import errors as cerrors
7
from flask_babel import lazy_gettext
8
9
10
class CustomErrorHandler(cerberus.errors.BasicErrorHandler):
11
    messages = cerberus.errors.BasicErrorHandler.messages.copy()
12
    messages.update({
13
        cerrors.REQUIRED_FIELD.code: lazy_gettext("Required field"),
14
        cerrors.UNKNOWN_FIELD.code: lazy_gettext("Unknown field"),
15
        cerrors.DEPENDENCIES_FIELD.code: lazy_gettext("Field '{0}' is required"),
16
        cerrors.DEPENDENCIES_FIELD_VALUE.code: lazy_gettext("Depends on these values: {constraint}"),
17
        cerrors.EXCLUDES_FIELD.code: lazy_gettext("{0} must not be present with '{field}'"),
18
19
        cerrors.EMPTY_NOT_ALLOWED.code: lazy_gettext("Field should not be empty"),
20
        cerrors.NOT_NULLABLE.code: lazy_gettext("Field should not be empty"),
21
        cerrors.BAD_TYPE.code: lazy_gettext("Must be of {constraint} type"),
22
        cerrors.ITEMS_LENGTH.code: lazy_gettext("Length of list should be {constraint}, it is {0}"),
23
        cerrors.MIN_LENGTH.code: lazy_gettext("Min length is {constraint}"),
24
        cerrors.MAX_LENGTH.code: lazy_gettext("Max length is {constraint}"),
25
26
        cerrors.REGEX_MISMATCH.code: lazy_gettext("Value does not match regex '{constraint}'"),
27
        cerrors.MIN_VALUE.code: lazy_gettext("Min value is {constraint}"),
28
        cerrors.MAX_VALUE.code: lazy_gettext("Max value is {constraint}"),
29
        cerrors.UNALLOWED_VALUE.code: lazy_gettext("Unallowed value {value}"),
30
        cerrors.UNALLOWED_VALUES.code: lazy_gettext("Unallowed values {0}"),
31
        cerrors.FORBIDDEN_VALUE.code: lazy_gettext("Unallowed value {value}"),
32
        cerrors.FORBIDDEN_VALUES.code: lazy_gettext("Unallowed values {0}"),
33
34
        cerrors.COERCION_FAILED.code: lazy_gettext("Field '{field}' cannot be coerced"),
35
        cerrors.RENAMING_FAILED.code: lazy_gettext("Field '{field}' cannot be renamed"),
36
        cerrors.READONLY_FIELD.code: lazy_gettext("Field is read-only"),
37
        cerrors.SETTING_DEFAULT_FAILED.code: lazy_gettext("Default value for '{field}' cannot be set: {0}"),
38
39
        cerrors.MAPPING_SCHEMA.code: lazy_gettext("Mapping doesn't validate subschema: {0}"),
40
        cerrors.SEQUENCE_SCHEMA.code: lazy_gettext("One or more sequence-items don't validate: {0}"),
41
        cerrors.KEYSCHEMA.code: lazy_gettext("One or more properties of a mapping  don't validate: {0}"),
42
        cerrors.VALUESCHEMA.code: lazy_gettext("One or more values in a mapping don't validate: {0}"),
43
44
        cerrors.NONEOF.code: lazy_gettext("One or more definitions validate"),
45
        cerrors.ONEOF.code: lazy_gettext("None or more than one rule validate"),
46
        cerrors.ANYOF.code: lazy_gettext("No definitions validate"),
47
        cerrors.ALLOF.code: lazy_gettext("One or more definitions don't validate"),
48
    })
49
50
    def __init__(self, tree=None, custom_messages=None):
51
        super().__init__(tree)
52
        self.custom_messages = custom_messages or {}
53
54
    def format_message(self, field, error):
55
        tmp = self.custom_messages
56
        for i, x in enumerate(error.schema_path):
57
            try:
58
                tmp = tmp[x]
59
            except KeyError:
60
                if i == len(error.schema_path) - 1 and 'any' in tmp:
61
                    return tmp['any']
62
                return super().format_message(field, error)
63
        if isinstance(tmp, dict):
64
            return super().format_message(field, error)
65
        else:
66
            return tmp
67
68
69
class Validator(cerberus.Validator):
70
    """Usage:
71
    schema = {"name": {"minlength": 2, "error_messages": {"minlength": "Custom too few"}}}
72
    v = Validator(schema)
73
    v.validate({"q": "0"})  # => False
74
    v.errors  # => {'q': ['Custom too few']}
75
    """
76
77
    def __init__(self, *args, **kwargs):
78
        if args:
79
            if 'schema' in kwargs:
80
                raise TypeError("got multiple values for argument 'schema'")
81
            schema = args[0]
82
        else:
83
            schema = kwargs.pop('schema')
84
85
        if isinstance(schema, dict):
86
            schema = copy.deepcopy(schema)
87
            self.populate_custom_messages(schema)
88
            args = [schema] + list(args[1:])
89
90
        kwargs['error_handler'] = CustomErrorHandler(custom_messages=self.custom_messages)
91
        if 'purge_unknown' not in kwargs:
92
            kwargs['purge_unknown'] = True
93
        super().__init__(*args, **kwargs)
94
        self.custom_messages = {}
95
        self._allowed_func_caches = {}
96
97
    def populate_custom_messages(self, schema):
98
        self.custom_messages = {}
99
        queue = [(schema, self.custom_messages)]
100
        while queue:
101
            item, msgs = queue.pop()
102
            if 'error_messages' in item:
103
                assert isinstance(item['error_messages'], dict)
104
                msgs.update(item.pop('error_messages'))
105
            for k, v in item.items():
106
                if isinstance(v, dict):
107
                    msgs[k] = {}
108
                    queue.append((v, msgs[k]))