0

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
  • Since JSON is a subset of YAML, changing to JSON will only solve your problem if your YAML data is bad. – Klaus D. Sep 15 '18 at 03:46

1 Answers1

1

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.

funky-future
  • 3,716
  • 1
  • 30
  • 43
  • If you look at how it is done using JSON in the linked SO [https://stackoverflow.com/questions/50133185/normalizing-string-to-date-in-cerbrus], you will see that I am following the exact pattern, only replacing JSON with YAML and it does not work. I basically have 2 questions: 1) How do I specify coerce functions in YAML, when in JSON you can just decorate it quotes? 2) Why in the first place do we need to specify coerce functions for date and datetime? '2017-10-01' is a standard date and that should have parsed properly when the type is set to 'date'. Correct? – Jayman Dalal Sep 17 '18 at 19:32
  • No, there are.more differences, e.g. what you refer to is not JSON but Python. 1) Not at all. 2) See the answer to the question you refer to. – funky-future Sep 18 '18 at 08:42