How to define coerce functions in YAML for python cerberus validator library

1k views Asked by At

I am trying to define my validator schema for python cerberus library in YAML since it is more human readable. I ran into an issue where if i try to define coerce function in YAML, I get the a SchemaError. Starting with example from Normalizing string to date in cerbrus, I modified it to use YAML schema.

import datetime
import yaml
st = '''
start_date: 
    type: datetime
    coerce: to_date
'''
schema = yaml.load(st)
v = cerberus.Validator()
to_date = lambda s: datetime.strptime(s, '%Y-%m-%d')
v.schema = schema
v.validate({'start_date': '2017-10-01'})

I get the error:

SchemaError: {'start_date': [{'coerce': ['none or more than one rule validate', {'oneof definition 0': ['must be of callable type'], 'oneof definition 1': ['must be of list type'], 'oneof definition 2': ['unallowed value to_Date']}]}]}

Is defining coerce functions supported with YAML based schema or do i need to switch back to using JSON?

1

There are 1 answers

2
funky-future On

You're creating a lambda function in the global scope of the module. The Cerberus validator doesn't know that you mean that one when you refer 'to_date'. Hence you need to define the coercer within a Validator subclass. Here is the relevant documentation.