这是一个有效的结构,或者我错过了什么

时间:2013-08-12 21:05:54

标签: python-2.7 yaml voluptuous

我有这个YAML文件。我有必需和可选键,还有可选块,比如'linux','http'等等。

---
project:
    name: lolproj
    url: http://wiki.tld/lolproj
contact:
    name: FooBar
    email: foobar@gmail.com
plugins:
    linux:
        settings:
            disk:
                critical: 90
                warning: 80
    http:
...

我正在以这种方式加载和验证它:

from voluptuous import *

def main():

    with open('mytiny.yaml', 'r') as f:
        mon = yaml.safe_load(f)

    project =  {
        Required('name'): All(str, Length(min=5), msg="Must be a string!"),
        Required('url'): All(str, Length(min=5))
    }

    contact = {
        Required('name'): All(str, Length(min=5)),
        Required('email'): All(str, Length(min=5)),
    }

    disk_settings = {
            'warning': int,
            'critical': int,
    }

    plugins = ['linux','http','mysql']

    schema = Schema({
        Required('project'): project,
        Required('contact'): contact,
        Optional('plugins'): plugins,
            Optional('settings'): {
                Optional('disk'): disk_settings,
            }
    })

但是我收到了这个错误:

Traceback (most recent call last):
  File "./readmon.py", line 143, in <module>
    main()
  File "./readmon.py", line 43, in main
    schema(mon)
  File "/usr/local/lib/python2.7/site-packages/voluptuous.py", line 207, in __call__
    return self._compiled([], data)
  File "/usr/local/lib/python2.7/site-packages/voluptuous.py", line 386, in validate_dict
    return base_validate(path, iteritems(data), out)
  File "/usr/local/lib/python2.7/site-packages/voluptuous.py", line 287, in validate_mapping
    raise MultipleInvalid(errors)
voluptuous.MultipleInvalid: expected a list for dictionary value @ data['plugins']

所以,看起来我做的事情非常糟糕。对此有何提示? 问题是,我希望有类似的东西:

['plugins'] ['linux'] ['settings'] ['disk'],或['plugins'] ['http'] ['settings'] ['disk']是'linux' or'http'变量字段带有可选设置。

丰富的文档不是新手友好的:/

1 个答案:

答案 0 :(得分:1)

刚刚将YAML布局更改为

"
...


plugins:
    linux:
        disk:
            critical: 90
            warning: 80
        exec:
            exitcode: 0
    http:
        url: http://127.0.0.1
        port: 8080
        status: 200

...
"

并将其验证为

''' PLUGINS SETUP
'''
disk_settings = {
    Optional('critical'): int,
    Optional('warning'): int,
    Optional('volume'): str,
}

exec_settings = {
    Optional('exitcode'): int,
}

linux_settings = {
    Optional('disk'): disk_settings,
    Optional('exec'): exec_settings,
}

http_settings = {
    Optional('url'): str,
    Optional('port'): int,
    Optional('status'): int,
}

plugins = {
    Optional('linux'): linux_settings,
    Optional('http'): http_settings,
}


''' CORE SCHEMA
'''
schema = Schema({
    Required('project'): project,
    Required('contact'): contact,
    Optional('plugins'): plugins,
})

它正在工作:)