Use Cerberus Schemas to Automate Documentation

238 Views Asked by At

We are using cerberus extensively to validate json configuration files. We therefore have a wide range of schemas, which define how these json documents should be formatted.

We would like to be able to use these schemas to auto-generate some documentation for the users who may need to create these json files.

At the moment, we keep separate pages of documentation around all of the different config formats that we have, however these can sometimes drift out of date if a change in made to the code that is not picked up that it requires a change to the documentation, and also requires the same piece of information to be updated in two places. By auto-generating from the schemas, the docs would always be up to date and guaranteed to reflect the actual code, and it would avoid the need to update in multiple places.

We are also using Sphinx to auto generate docs from our codebase, based on Docstrings in out .py files, and separate .md files.

It feels that using the Cerberus schema files to create a "human readable" documentation file for each schema should be reasonably straight forward, but I have not been able to find any documentation for this within either Cerberus or Sphinx. Does anyone know if there is some native functionality in either of these packages that would achieve this that I am missing, or another way or example of achieving this?

1

There are 1 best solutions below

0
On

I've had a similar idea, though I haven't fully implemented it yet. As a start what I've done is create my own custom validator subclass with a custom validation 'description'. This validation does nothing, but allows adding a 'description' field to my schemas, which I intend to use later for documentation purposes.

class ConfigValidator(Validator):
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

def _validate_description(self, constraint:str, field:str, value:str) -> None:
    """
    Enables the use of the key 'description' in schemas in order to add descriptions to fields. Useful for automated documentation in the future. 
    Does no validation.
    
    Args:
        constraint (str): The name constraint applied.
        field (str): The name of the field.
        value (dict): The value of the field.

    The rule's arguments are validated against this schema:
    {'type': 'string'}
    """
    pass