python-3.x - 是否可以在 cerberus、Python 中设置条件验证?
问题描述
我使用 Python 包cerberus来验证我的有效负载这是我的问题:
仅当来自另一个模式的某些字段具有精确值时,我才需要设置一个字段。就像是:
"key2": {
"type": "string",
"required": \\\ true if dict1.key1 == 'valueX' else false \\\
}
所以我的架构应该是这样的:
"dict1": {
"type": "dict",
"schema": {
"key1": {
"type": "string",
"required": true
}
}
},
"dict2": {
"type": "dict",
"schema": {
"key2": {
"type": "string",
"required": \\\ true if dict1.key1 == 'valueX' else false \\\
}
}
}
有人知道方法,如何实现吗?谢谢
解决方案
我已经阅读了文档,但还没有找到答案。在您的示例中,我不确定它是否真的有效。此外,我认为依赖项的工作方式与我的示例不同。但也许我错了。
看起来子模式中的依赖项不起作用。您的示例返回错误消息:
from cerberus import Validator
schema = {"dict1": {
"type": "dict",
"schema": {
"key1": {
"type": "string",
"required": True,
"allowed": ["valueX"]
}
}
},
"dict2": {
"type": "dict",
"schema": {
"key2": { # required if dependency matches
"type": "string",
"dependencies": {
"dict1.key1": ["valueX"]
}
}
}
}
}
payload = {
"dict1": {
"key1": 'valueX'
},
"dict2": {
"key2": 'some_value'
}
}
validator = Validator(schema)
if validator(payload):
print('Super!')
else:
print(str(validator.errors))
有错误:
{'dict2': [{'key2': ["depends on these values: {'dict1.key1': ['valueX']}"]}]}
但是当我尝试为“dict2”设置依赖项时它起作用了
schema = {"dict1": {
"type": "dict",
"schema": {
"key1": {
"type": "string",
"required": True#,
#"allowed": ["valueX"]
}
}
},
"dict2": {
"type": "dict",
"dependencies": {
"dict1.key1": "sms"
},
"schema": {
"key2": { # required if dependency matches
"type": "string"
}
}
}
}
如果我错了,请告诉我。该解决方案真的会帮助我。谢谢
推荐阅读
- python - 如果匹配来自同一行列的复制值,则比较并循环第二个数据帧中时间间隔的每一行
- javascript - Typescript - TypeError this.renderCell 不是函数
- regex - 使用 Google 表格 RE2 删除 2 个字符串之间的所有内容
- binary - 什么文件格式有这个神奇的标题?
- reactjs - 将 React 组件渲染为 svg
- javascript - 来自子 HTML 的变量集未反映在控制器中
- python - 对每一行应用一个函数
- javascript - 如何在 onClick 中调用异步函数(按钮单击)
- typescript - 使用接口扩展多个类不起作用
- java - Mockito:验证是否执行了任何线程中指定的方法?