从一个或多个分层配置源构建配置存储的库
项目描述
这是一个Python库,用于从一个或多个分层配置源构建配置存储。这些通常是文件,包括对YAML、TOML和JSON的支持,并易于添加其他格式。源不一定是文件,包括对环境变量和命令行选项的支持。
除了易于使用的接口外,配置信息还以嵌套的简单Python数据类型的形式提供,以便您可以使用您选择的工具验证配置的架构。
快速入门
要安装库,请执行以下操作:
pip install configurator[yaml,toml]
以下是处理分层默认值、系统范围配置以及可选的每个用户配置的示例
from configurator import Config
defaults = Config({
'cache': {
'location': '/tmp/my_app',
'max_files': 100,
},
'banner': 'default banner',
'threads': 1,
})
system = Config.from_path('/etc/my_app/config.yaml')
user = Config.from_path('~/.my_app.yaml', optional=True)
config = defaults + system + user
现在,如果我们想从环境和命令行参数获取配置,以覆盖配置文件中提供的配置,可以这样做:
import os
from argparse import ArgumentParser
from configurator import convert, target, required
config.merge(os.environ, {
convert('MYAPP_THREADS', int): 'threads',
required('MYAPP_CACHE_DIRECTORY'): 'cache.location',
})
parser = ArgumentParser()
parser.add_argument('--threads', type=int)
parser.add_argument('--max-files', type=int)
args = parser.parse_args()
config.merge(args, {
'threads': 'threads',
'max_files': 'cache.max_files',
})
为了检查我们积累的配置是否合理,我们可以使用数据验证库,如 Voluptuous
from os.path import exists
from voluptuous import Schema, All, Required, PathExists
schema = Schema({
'cache': {'location': All(str, PathExists()), 'max_files': int},
'banner': Required(str),
'threads': Required(int),
})
schema(config.data)
所以,有了所有这些,我们可以使用以下配置源:
>>> import os, sys >>> print(open('/etc/my_app/config.yaml').read()) cache: location: /var/my_app/ <BLANKLINE> >>> os.environ['MYAPP_THREADS'] '2' >>> os.environ['MYAPP_CACHE_DIRECTORY'] '/var/logs/myapp/' >>> sys.argv ['myapp.py', '--threads', '3', '--max-files', '200']
有了上述配置源,我们最终会得到一个配置存储库,我们可以按以下方式使用它:
>>> config.cache.location '/var/logs/myapp/' >>> config.cache.max_files 200 >>> config.banner 'default banner' >>> config.threads 3
项目详情
下载文件
下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源代码分发
configurator-3.2.0.tar.gz (35.5 kB 查看散列)
构建分发
configurator-3.2.0-py3-none-any.whl (12.7 kB 查看散列)