导航

动态构建ConfigObj的configspec

Posted on 2011-11-12 23:50  Morya  阅读(570)  评论(0)    收藏  举报

validate模块用来验证ini文件是否合法,内部设定的值是否合乎逻辑。

但是我们的配置文件有些section是可选的,所以后来想到用下面这种办法来动态构建一个spec文件。

 

示例代码如下:

 

#coding:utf-8

'''
test configuration of float in same min max value range
'''

from pprint import pprint

from StringIO import StringIO

from configobj import ConfigObj, ConfigObjError, flatten_errors
from validate import Validator


cfg_file = StringIO('''
option = opt1 # or opt2 
version = 1.0
[sec1]
vv = 1
[sec2]
vv = 1
[sec3]
vv = 1
''')

# base config, these always appear
base_spec = '''
version = float(min=2.0, max=2.0)
link_type = option("telnet", "ssh")

[db]
ip = ip_addr
sid = string(1,24)
username = string(1,24)
password = string(1,24)
'''

optional_sec1_spec = '''
[optional_sec1]
sec1_opt1 = string(1, 24)
'''

sec1_2_namelist = [
                   'sec1',
                   'sec2',
                   ]
sec1_spec = '''
[{}]
enable=boolean
'''

sec3_spec = '''
{}
sleeptime=float(0, 100)'''.format(sec1_spec)
sec3_4_5_namelist= ['sec3',
                    'sec4',
                    'sec5',
                    ]

def main():
    vldt = Validator()
    # first configuration read from file
    # no spec has been bind to it
    cfg1 = ConfigObj(cfg_file)
    spec_file = StringIO()
    spec = spec_file
    spec.write(base_spec)
    if 'optional_sec1' in cfg1:
        spec.write(optional_sec1_spec)
    
    for section in sec1_2_namelist:
        if section in cfg1:
            spec.write(sec1_spec.format(section))
    
    for section in sec3_4_5_namelist:
        if section in cfg1:
            spec.write(sec1_spec.format(section))
    
    print spec.getvalue()
    return

    cfg = ConfigObj(cfg1, configspec=spec)
    
    result = cfg.validate(vldt, True)
    # TODO: flatten_errors
    if result is not True:
        pprint(result)


if __name__ == '__main__':
    try:
        main()
    except ConfigObjError as err:
        print err.errors