使用cerberus进行递归数据验证时出现TypeError

时间:2019-10-21 12:40:00

标签: python cerberus

我正在使用cerberus 1.3.1验证一些表示表达式列表的数据。列表中的每个表达式都可以是变量或二进制运算符表达式。二进制运算符表达式又可以将另一个表达式作为左和/或右项,因此数据是递归的。我正在使用cerberus.schema_registry.add来处理递归。

下面是一些示例代码:

binop = {
    "binop": {
        "type": "dict",
        "schema": {
            "left": {
                "schema": "expr",
                "required": True
            },
            "right": {
                "schema": "expr",
                "required": True
            },
            "operator": {
                "type": "string",
                "required": True
            },
        },
    }
}

var = {
    "variable": {
        "type": "dict",
        "schema": {
            "name": {
                "type": "string"
            }
        }
    }
}

expr = {
    "expr": {
        "type": "dict",
        "schema": {
            "anyof": [
                {"schema": var},
                {"schema": binop}
            ]
        }
    }
}

cerberus.schema_registry.add('expr', expr)
schema = {"expressions": {"type": "list", "schema": "expr"}}

v = cerberus.Validator(schema)

doc = {
    "expressions": [
        {
            "expr": {
                "binop": {
                    "left": {"expr": {"variable": {"name": "var1"}}},
                    "right": {"expr": {"variable": {"name": "var2"}}},
                    "operator": "+"
                }
            }
        },
        {"expr": {"variable": {"name": "var3"}}},
        {"expr": {"variable": {"name": "var4"}}}
    ]
}
print(v.validate(doc))

运行此代码时,出现以下错误:

Traceback (most recent call last):
  File "test.py", line 71, in <module>
    print(v.validate(doc))
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 990, in validate
    self.__normalize_mapping(self.document, self.schema)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 671, in __normalize_mapping
    self.__normalize_containers(mapping, schema)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 757, in __normalize_containers
    self.__normalize_sequence_per_schema(field, mapping, schema)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 826, in __normalize_sequence_per_schema
    result = validator.normalized(document, always_return_document=True)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 646, in normalized
    self.__normalize_mapping(self.document, self.schema)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 660, in __normalize_mapping
    self.__normalize_rename_fields(mapping, schema)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 864, in __normalize_rename_fields
    self._normalize_rename(mapping, schema, field)
  File ".venv/lib/python3.6/site-packages/cerberus/validator.py", line 877, in _normalize_rename
    if 'rename' in schema[field]:
TypeError: argument of type 'NoneType' is not iterable

我在做什么错或者这是一个cerberus bug?

0 个答案:

没有答案