Important: Always read the processed data from v.document, not your input variable.
schema={# Sets value if missing from config'port':{'type':'integer','default':8080},# Converts types (e.g., handles env variables loaded as strings)'retries':{'type':'integer','coerce':int},# Cleans strings automatically'api_key':{'type':'string','coerce':lambdas:s.strip()}}
🎛️ Advanced Control Flow
Dependencies
Field validation depends on the state of another field.
schema={'use_ssl':{'type':'boolean'},'ssl_cert':{'type':'string','dependencies':'use_ssl'}# Only required if use_ssl is True}
Extend the Validator class to write custom business logic (e.g., testing if a file path actually exists).
importosfromcerberusimportValidatorclassConfigValidator(Validator):def_validate_is_existing_file(self,is_existing_file,field,value):"""
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""ifis_existing_fileandnotos.path.isfile(value):self._error(field,f"Path '{value}' does not exist or is not a file.")# Usageschema={'config_path':{'type':'string','is_existing_file':True}}v=ConfigValidator(schema)
fromcerberusimportValidatorclassConfigValidator(Validator):# ┌── 'is_existing_file' rule argument (e.g., True)# │ ┌── Current field name (e.g., 'config_path')# │ │ ┌── The derived value from your data# ▼ ▼ ▼def_validate_is_existing_file(self,is_existing_file,field,value):print(f"Checking field '{field}' with value: {value}")schema={'config_path':{'type':'string','is_existing_file':True}}# 1. Instantiate the validator with your rulesv=ConfigValidator(schema)# 2. Define your input dataconfig_data={'config_path':'/etc/settings.conf'# <── This is where 'value' comes from!}# 3. Trigger the validation loopv.validate(config_data)# Output: Checking field 'config_path' with value: /etc/settings.conf
🧠 How Cerberus Maps This Behind the Scenes
v.validate(config_data) tells Cerberus to look at the config_data dictionary.
It processes the key config_path.
It sees the custom rule is_existing_file: True in the schema.
It calls your method _validate_is_existing_file and automatically maps the arguments:
is_existing_file = True (from the schema)
field = 'config_path' (the key name)
value = '/etc/settings.conf' (the key’s value in your data)