简体   繁体   中英

Normalize nested dict in Cerberus

I'd like to have default values in nested dicts with Cerberus normalize function. Unfortunately it's not working. I have code such as:

from yaml import load, Loader
from cerberus import Validator

text_schema = """
server:
  type: dict
  required: True
  schema:
    host:
      required: True
      type: string
    api:
      type: dict
      required: True
      schema:
        enabled:
          type: boolean
          required: True
          default: True
"""

testyaml = """
server:
  host: hostname
"""
schema = load(text_schema, Loader=Loader)
doc = load(testyaml, Loader=Loader)
v = Validator(schema, purge_unknown=True)
print(v.normalized(doc))

I end up with:

{'server': {'host': 'hostname'}}

and I'd expect to have:

{'server': {'host': 'hostname', 'api': {'enabled': true}}}

Is this possible?

Not really sure if this is proper, but simply adding an empty default value to the api key works.

text_schema = """
server:
  type: dict
  required: True
  schema:
    host:
      required: True
      type: string
    api:
      type: dict
      required: True
      default: {}
      schema:
        enabled:
          type: boolean
          required: True
          default: True
"""

Using the above schema, I get: {'server': {'host': 'hostname', 'api': {'enabled': True}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM