Python 架构或 ()

Python Schema Or()

我想知道是否有人使用过 pypi 模块 Schema 并且可以帮助我?

所以我有一个要验证的 schema,我正在使用 Or 方法,这很好,因为它允许您有 or 选项。然而,直到后来我才意识到,选项中允许所有选项,而不仅仅是一个选项。

例如:

from schema import Schema, Or
test_schema = Schema({Or("fist", "schema"): str, "second": int})
test_validate = {"first": "test", "schema": "check", "second": 15}
test_schema.validate(test_validate)
{"first": "test", "schema": "check", "second": 15}

从模块来看,这是预期的结果,但我想知道是否有办法强制选择一个而不是两个。从文档中我看不到它。如果有人知道如何做到这一点,我将不胜感激。

所以,我想我需要学习一些关于阅读文档的知识。因此,在 Or 的架构文档中,他们有一个 only_one 选项,但我不确定它是如何工作的,但似乎您需要在调用或使其工作时将其指定为参数。

from schema import Schema, Or
test_schema = Schema({Or("fist", "schema", only_one=True): str, "second": int})
test_validate = {"first": "test", "schema": "check", "second": 15}

然后我会收到一条错误消息,提示存在多个密钥。我将把这作为一个教训,尽管我断断续续地做了大约 2 年多了,但我仍然有很多关于编程文档的知识要学习:)。