'Cerberus - Validate field only if flag is set

Assume the Cerberus Schema with some container aggregating boolean flags to control verification of another fields like below.

flags = {
    "flags": 
    {
        "enable_foo": 
        {
            "type": "boolean"
        }, 
        "enable_bar": 
        {
            "type": "boolean"
        }
    }
}

foo = {
    # shall be verified only when flags.enable_foo is true.
    "some_foo_field": {
        "type": "integer",
        "min": 1,
        "nullable": True,  # default value is null
    }
}

bar = {
    # shall be verified only when flags.enable_bar is true.
    "some_bar_field": {
        "type": "integer",
        "min": 1,
        "nullable": True,  # default value is null
    }
}

schema = {**flags, **foo, **bar}

How may I validate foo and bar only when proper flags are set?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source