0

使用该cerberus库进行验证,我想知道自定义规则如何检查输入是否是只有一个元素的列表。如果是这种情况,则应将值更改为单个值(值强制)。

这是我的尝试,它不起作用。

from cerberus import Validator


class MyValidator(Validator):
    def _validate_is_one_elem_list(self, is_one_elem_list, field, value):
        """{'type': 'boolean'}"""

        if is_one_elem_list and isinstance(value, list) and len(value) == 1:
            self.value = value[0]  # self.value doesn't exist, so that's wrong. How to do better?


v = MyValidator()

schema = {"amount": {"is_one_elem_list": True, "type": "list"}}
print(v.validated({"amount": [10]}, schema))

输出是{'amount': [10]}
但是,它应该阅读{'amount': 10}

4

1 回答 1

0

替换self.value = value[0]self.document[field] = value[0]

使用功能调整方法check_withhttps://docs.python-cerberus.org/en/stable/validation-rules.html#check-with)进一步简化了整个事情。

from cerberus import Validator


class MyValidator(Validator):
    def _check_with_is_one_elem_list(self, field, value):

        if isinstance(value, list) and len(value) == 1:
            self.document[field] = value[0]


v = MyValidator()

schema = {"amount": {"check_with": "is_one_elem_list", "type": "list"}}
assert v.validated({"amount": [10]}, schema) == {"amount": 10}
于 2020-05-11T14:46:22.353 回答