所以我没有一个好的答案,但我有一个解释,给你一个不太有趣的解决方法。
您可以通过查看docs 开始了解这里的问题。如果您查看info 属性,您会看到它提到了批量验证如何将它们的个别错误塞入此处。您遇到的问题是您期望的 UNALLOWED_VALUE 错误被其他错误所掩盖。要更清楚地看到这一点,您可以查看正在返回的底层错误对象(使用 ._errors 而不是 .errors)。当你这样做时,你会看到:
[ValidationError @ 0x1fe369bcbe0 ( document_path=('sort',),schema_path=('sort', 'schema'),code=0x82,constraint={'type': 'dict', 'schema': {'property': {'type': 'string', 'required': True, 'allowed': ['test']}, 'direction': {'type': 'string', 'required': True, 'allowed': ['asc', 'desc']}}},value=[{'property': '', 'direction': 'asc'}, {'property': '', 'direction': 'desc'}],info=([ValidationError @ 0x1fe369bc4f0 ( document_path=('sort', 0),schema_path=('sort', 'schema', 'schema'),code=0x81,constraint={'property': {'type': 'string', 'required': True, 'allowed': ['test']}, 'direction': {'type': 'string', 'required': True, 'allowed': ['asc', 'desc']}},value={'property': '', 'direction': 'asc'},info=([ValidationError @ 0x1fe369bcb80 ( document_path=('sort', 0, 'property'),schema_path=('sort', 'schema', 'schema', 'property', 'allowed'),code=0x44,constraint=['test'],value="",info=('',) )],) ), ValidationError @ 0x1fe369bcdc0 ( document_path=('sort', 1),schema_path=('sort', 'schema', 'schema'),code=0x81,constraint={'property': {'type': 'string', 'required': True, 'allowed': ['test']}, 'direction': {'type': 'string', 'required': True, 'allowed': ['asc', 'desc']}},value={'property': '', 'direction': 'desc'},info=([ValidationError @ 0x1fe369bcbb0 ( document_path=('sort', 1, 'property'),schema_path=('sort', 'schema', 'schema', 'property', 'allowed'),code=0x44,constraint=['test'],value="",info=('',) )],) )],) )]
看起来并不漂亮,但是如果您分析它,您会发现还有其他错误包裹着您想要查看的错误。因此,当您简单地使用简单的UNALLOWED_VALUE in v.errors 检查进行测试时,它会失败。如果您一直深入研究,您可以粗略地在您的特定示例代码中完成这项工作。您需要一张支票,例如:cerberus.errors.UNALLOWED_VALUE in v._errors[0].info[0][0].info[0]。显然,这很恶心,我不推荐它。
我不太确定库中是否有一种机制可以更好地处理此问题,但作为一种解决方法,您可以简单地检查您发现的错误的 info 属性,以查找更多 ValidationError 类的实例。这不干净,也许您可以使用 Validator 类 error_handler 参数做更多事情,但希望这会有所帮助!