处理多源分布式配置的包
distribute-config的Python项目详细描述
分发配置
处理多源分布式配置的包
这个包处理python中的多源配置问题。对于包含一组配置变量的python程序, 此包将通过查找yaml配置文件来填充这些配置变量的值,然后将覆盖 变量通过查找匹配的环境变量,然后,如果程序是用一些参数启动的,则将通过加载这些变量再次覆盖配置值
此外,这个包允许您在多个python文件中定义配置变量,使用名称空间系统,这样您就不会意外地破坏配置的其他部分,因此配置保持在需要它的代码附近,您可以通过导入新的python文件来更新配置。
示例
让下面的python程序app.py:
fromdistribute_configimportConfigConfig.define_int("nb",1,"some number")Config.define_str_list("list",["a","b","c"],"some list")Config.define_enum("logger","debug",["info","debug","warn"],"the logger level")Config.load_conf()print(Config.get_dict())
使用python app.py
运行它将创建一个文件config.yml:
list: - a - b - c nb: 1 logger: debug
显示:{'nb': 1, 'list': ['a', 'b', 'c'], 'logger' : 'debug'}
现在如果我们更新config.yml:
list: - a - b nb: 2
python app.py
将打印{'nb': 2, 'list': ['a', 'b']}
NB=3 python app.py
将打印{'nb': 3, 'list': ['a', 'b']}
NB=3 python app.py --nb 4
将打印{'nb': 4, 'list': ['a', 'b']}
此外,python app.py --help
显示所有可能的变量和有用的注释
示例2:命名空间
将app.py更改为:
fromdistribute_configimportConfigConfig.define_int("nb",1,"some number")withConfig.namespace("set1"):Config.define_int("nb",2,"some other number")withConfig.namespace("set2"):Config.define_int("nb",3,"and again")Config.define_int("other.nb",4,"last")Config.load_conf()print(Config.get_dict())
运行python app.py
将显示{'nb': 1, 'set1': {'nb': 2, 'set2': {'nb': 3}}, 'other': {'nb': 4}}
创建的config.yml是:
nb: 1 other: nb: 4 set1: nb: 2 set2: nb: 3
python app.py
将打印{'nb': 1, 'set1': {'nb': 2, 'set2': {'nb': 3}}, 'other': {'nb': 4}}
SET1__SET2__NB=30 python app.py
将打印{'nb': 1, 'set1': {'nb': 2, 'set2': {'nb': 30}}, 'other': {'nb': 4}}
SET1__SET2__NB=30 python app.py --set1.set2.nb=40
将打印{'nb': 1, 'set1': {'nb': 2, 'set2': {'nb': 40}}, 'other': {'nb': 4}}
功能
- 配置支持单个变量(int、float、str、bool),也支持list(int、float、str)和enum
- 使用config.load_conf()加载配置时,可以指定要创建或加载的配置文件的名称,还可以指定不希望创建配置文件还是要更新当前配置文件的内容(添加新功能时使用)
测试
鼻测试-V