gpt4 book ai didi

python - Cerberus - 仅当满足依赖性时才需要字段

转载 作者:行者123 更新时间:2023-12-01 08:17:45 25 4
gpt4 key购买 nike

考虑以下架构

schema = {
"value_type":{
"type": "string", "required": True
},
"units": {
"type": "string",
"dependencies": {"value_type": ["float", "integer"]},
"required": True
}
}

我希望value_type 字段的值为 float整数

这是我想要实现的行为

v = Validator(schema)
v.validate({"value_type": "float", "units": "mm"}) # 1.
True
v.validate({"value_type": "boolean", "units": "mm"}) # 2.
False
v.validate({"value_type": "float"}) # 3.
False
v.validate({"value_type": "boolean"}) # 4.
True

上述架构仅返回前 3 种情况的预期结果。

如果我将 units 的定义(通过省略 "required": True)更改为

"units": {"type": "string", "dependencies": {"value_type": ["float", "integer"]}}

然后验证

v.validate({"value_type": "float"})  # 3.
True

返回True,这不是我想要的。

我查看了 documentation 中的 oneof 规则但找不到将其仅应用于 required 属性的方法。

我希望仅当满足依赖关系时,required 的值才为 True

我应该如何修改我的架构来实现这一目标?

最佳答案

由于您的变体跨越多个字段,*of 规则并不完全适合,特别是因为这些似乎是文档中的顶级字段。

我通常建议仍然有Python,并不是所有的东西都必须用模式来表达,所以你可以简单地定义两个有效的模式并针对它们进行测试:

schema1 = {...}
schema2 = {...}

if not any(validator(document, schema=x) for x in (schema1, schema2)):
boom()

这也比您最终得到的任何模式更容易理解。

或者,您可以使用 check_with 规则。该示例显示了两种不同的提交错误的方式,其中当错误仅呈现给人类时,后一种方式是首选,因为它们允许针对不同情况的自定义消息,同时缺乏有关错误的结构信息:

class MyValidator(Validator):
def _check_with_units_required(self, field, value):
if value in ("float", "integer"):
if "units" not in self.document:
self._error("units", errors.REQUIRED_FIELD, "check_with")
else:
if "units" in self.document:
self._error(
"units", "The 'units' field must not be provided for value "
"types other than float or integer."
)

schema = {
"value_type": {
"check_with": "units_required",
"required": True,
"type": "string"
},
"units": {
"type": "string",
}
}

validator = MyValidator(schema)

assert validator({"value_type": "float", "units": "mm"})
assert not validator({"value_type": "boolean", "units": "mm"})
assert not validator({"value_type": "float"})
assert validator({"value_type": "boolean"})

关于python - Cerberus - 仅当满足依赖性时才需要字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com