Search code examples
pythonvalidationcerberus

How can I produce a warning with ceberus if a key is missing?


Cerberus allows for required fields but I'd like to have a "preferred" class of fields such that a warning message is logged if they're missing. Some ideas I have that don't seem great are the following:

  1. I could extend the validator with a custom rule, but these are called with field and value arguments, making me suspect that this function would be called on missing fields. __validate_required_fields which is called on the document to generate missing fileds would be more ideal, but I'm not sure how to hook that in.

  2. Cerberus offers a check_with option but again, I'm not sure if this would be called on missing fields.

  3. I could try to mark these as required and do the tracing in an error handler. This is not ideal because validation should not fail if "preferred" fields are missing.


Solution

    1. Your suspicion is correct, fields that are not in the document are not validated fully. And __validate_required_fields isn't designated to be overridden (name mangling would fail due to two leading __).

    2. It is not as in 1.

    3. That would best be done by overriding the validate method and post-process the various (!) error containers.

    I think the simplest solution would be to validate against two different schemas, one that checks hard and one that you get the warnings from.