[Python] How to validate only part of a document with Cerberus?

Discussão em 'Python' iniciado por Stack, Fevereiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I use Cerberus to validate a loaded configuration file. The user may make changes to that configuration within the program, however, and when they do, I’d like to validate only that change with Cerberus – not validate the whole document in vain, when I know that the rest hasn’t changed.

    Take the following minimal example:

    import cerberus

    SCHEMA = {
    'a': {'type': 'string'},
    'b': {'type': 'integer', 'allowed': (39, 93)}
    }

    v = cerberus.Validator(SCHEMA)

    config = {
    'a': 'Wow!',
    'b': 39
    }

    print(v.validate(config), v.errors) # So far, so good.


    config['b'] = 93 # Then the user changes only one property…

    # How do I now validate *only* config['b'], without validating config['a']?


    I considered using cerberus.Validator._get_child_validator, which by name would appear to do exactly what I ask, but apparently it still checks the whole document:

    child = v._get_child_validator(document_crumb='b')

    # This is wrong, but I don’t want to validate it – it’s just to illustrate that it *is* being validated.
    config['a'] = None

    print(child.validate(config), v.errors) # False, {'a': ['null value not allowed']}


    How do I validate only the part that has changed?

    Continue reading...

Compartilhe esta Página