用于云本机应用程序的配置管理器,支持存储在内存、文件和数据库中的配置

config42的Python项目详细描述


Latest version onSupported Python versionsTravis Pipelines build statuscodecov

配置42

config42是一个完整的配置读取器和管理器。它的目标是从不同的来源读取配置:内存Dict对象、外部文件(YAML、JSON、INI、PYTHON对象)、SQL数据库(Postgres、MySQL、Oracle) 或者,密钥值数据存储(ETCD)

它被设计成可扩展的。不同的处理程序可以支持另一个数据存储。 欢迎所有公关

相关博客文章

安装

来源:(出血边缘)

pip install git+https://github.com/yurilaaziz/config42

来自pypi:(稳定)

pip install config42

入门

配置42抽象加载配置复杂度。让config42为您管理配置

使用环境变量

大多数容器化应用程序从环境变量更改行为以更改其行为。配置42易于处理。

这里是一个工作样本examples/docker

fromconfig42importConfigManagerenv_config=ConfigManager(prefix="MYAPP")# Access to configuration via the ConfigManager getterprint("username : {}".format(env_config.get('username')))print("nested key  : {}".format(env_config.get('secret.one')))

将变量导出到系统环境

exportMYAPP_USERNAME=yuri
exportMYAPP_SECRET_ONE=password
python app.py

将变量导出到流程环境

MYAPP_USERNAME=yuri2 python app.py

构建Docker映像后,可以通过将变量导出到容器环境中来运行应用程序

docker run  -e MYAPP_USERNAME=yuri -e MYAPP_SECRET_ONE=secret testconfig42:latest

使用Etcd处理程序

要从etcd数据存储加载配置,需要指定配置所在的keyspace,etcd主机和端口。

fromconfig42importConfigManagerfromconfig42.handlersimportEtcdconfig=ConfigManager(handler=Etcd,keyspace='/config')# config = ConfigManager(handler=Etcd, keyspace='/config', port=4001)# config = ConfigManager(handler=Etcd, keyspace='/config', host='127.0.0.1', port=4001)# config = ConfigManager(handler=Etcd, keyspace='/config', host=(('127.0.0.1', 4001), ('127.0.0.1', 4002), ('127.0.0.1', 4003)))

注意:Etcd处理程序使用python-etcd客户端 密钥空间之后的所有参数都传递给etcd.client类。

使用filehandler,从文件加载配置

frompprintimportpprintfromconfig42importConfigManagerfromconfig42.handlersimportFileHandler# Yaml filesconfig=ConfigManager(handler=FileHandler,path='files/config1.yml')#config = ConfigManager(handler=FileHandler, path='files/config1.yaml')# Json file #config = ConfigManager(handler=FileHandler, path='files/config1.json')#INI structure support only one level of nesting (Sections = { key: value }) #config = ConfigManager(handler=FileHandler, path='files/config.ini')CONFIG=config.as_dict()print("Configuration has been loaded")pprint(CONFIG)# Access to configuration via the ConfigManager getterprint("application_name : {}".format(config.get('application_name')))print("nested key : {}".format(config.get('nested.nestedkey.key2')))# Access to configuration via the as dict utility; it will dump configuration file to data store if updatedprint("user : {}".format(config.as_dict()['user']))# Access to configuration via the classic CONFIG global variableprint("application_name : {}".format(CONFIG['application_name']))print("nested key : {}".format(CONFIG['nested']['nestedkey']['key2']))

使用argparse,从命令行参数(sys.argv)加载配置

fromconfig42importConfigManagerfromconfig42.handlers.argparseimportArgparseschema=[dict(key="user",description="username"),dict(key="verbosity",description="verbosity level",choices=["debug","info"]),]config=ConfigManager(handler=Argparse,schema=schema)

请看一下example using Argparse's handler

实际用例

下面是instabot py项目的一个实际用途,该项目使用这个库作为配置管理器。

config42按优先级处理4个配置数据源:

  • 来自dict对象的默认配置
  • 以INSTABOT为前缀的环境变量
  • 值位于config.file中的本地文件(instabot_config_file)
  • Etcd数据存储

参考号:https://github.com/instabot-py/instabot.py

importlogging.configimportosfromconfig42importConfigManagerfrominstabot_py.default_configimportDEFAULT_CONFIGenv_config=ConfigManager(prefix="INSTABOT")logging.basicConfig(level=logging.DEBUGifenv_config.get("debug")elselogging.INFO)LOGGER=logging.getLogger(__name__)config=ConfigManager()config.set_many(DEFAULT_CONFIG)config.set_many(env_config.as_dict())config_file=config.get("config.file")config_etcd=config.get("config.etcd")ifconfig_file:ifconfig_file.startswith("/"):config_path=config_fileelse:cwd=os.getcwd()config_path=cwd+"/"+config_fileconfig.set_many(ConfigManager(path=config_path.replace('//','/')).as_dict())LOGGER.info("Setting configuration from {} : OK".format(config_file))ifconfig_etcd:ifnotconfig_etcd.get("keyspace"):raiseException("etcd Keyspace is mandatory")try:config.set_many(ConfigManager(**config_etcd).as_dict())LOGGER.info("Setting external configuration from {} : OK".format(config_file))exceptExceptionasexc:LOGGER.error("Setting external configuration from ({}) : NOT OK".format(",".join({key+"="+valueforkey,valueinconfig_etcd.items()or{}})))LOGGER.exception(exc)raiseexclogging.config.dictConfig(config.get("logging"))

要求

yaml配置文件

pip install Pyaml

ETCD数据存储

pip install python-etcd

偏差

运行测试和覆盖率需要以下软件包

pip install tox pytest-cov pytest flake8

pip install -r requirements/ci.txt
pip install -r requirements/tests.txt

使用示例

待办事项

  • 用狮身人面像读道

释放量

0.3.1

  • 添加设置默认变量功能

0.3

  • 添加环境处理程序

0.2

  • 添加Etcd处理程序
  • 添加ini yaml、json处理程序

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
对Java中的“this”操作符感到困惑   java更改Libgdx按钮外观   java返回到上一个开关案例   java返回带有可选对象的完全未来列表   java应该只在更新JPA中的整个实体时使用“合并”吗?   java如何将x个整数拆分为y个数组?   java HQL多where子句   java类“org.apache.activemq.jms.pool.PooledConnectionFactory”的哪个属性应该用于超时连接请求?   java运行servlet程序   JavaSpring数据JPA/REST更新子集合   eclipse工具,用于从源代码中提取java类层次结构和调用图(使用api)   java如何在Eclipse中打开Tomcat的自动重启?   java使用并发包中的同步器。FutureTask始终返回null   java Spring Boot@ExceptionHandler隐藏异常名称   java无法访问ActivityCompatApi23类文件   忙时无法将Java窗口置于最前面   java Play Framework 2.5.12从调用中获取方法