首页 > 解决方案 > 是否可以在 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 \\\
    }
  }
}

有人知道方法,如何实现吗?谢谢

标签: python-3.xvalidationconditional-statementscerberus

解决方案


我已经阅读了文档,但还没有找到答案。在您的示例中,我不确定它是否真的有效。此外,我认为依赖项的工作方式与我的示例不同。但也许我错了。

看起来子模式中的依赖项不起作用。您的示例返回错误消息:

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"
            }
        }
    }
}

如果我错了,请告诉我。该解决方案真的会帮助我。谢谢


推荐阅读