轻松处理项目中的配置文件
项目描述
配置处理程序
以简单的方式处理项目中的配置文件。
安装
> pip install config-handler
规则
规则1
使用 INI 文件进行配置。
关于这一点,请遵循 INI 文件语言:https ://en.wikipedia.org/wiki/INI_file
规则 #2
仅使用字符串、整数和布尔值。
如果您需要使用其他任何东西,那么设计是不正确的。
规则#3
不要将您的配置文件 (config.ini) 放在 git 存储库中。
相反,您有一个配置模板文件 (config.ini.template)。
规则 #4
配置文件应该只包含用户可以更改的内容。
如果您有永远不会改变的数据,请使用常量。
配置模板文件
这就是 config.ini.template 文件的样子:
config.ini.template 文件支持模板变量 ( ${project_root_path})。
用法
情景#1
您是第一次运行您的应用程序,但 config.ini 尚不存在。
所以你需要从 config.ini.template 文件创建它(如果需要,使用模板变量):
import os
from config_handler import ConfigHandler
template_config_variables = {
'project_root_path': os.path.join('path', 'to', 'project', 'root')
}
ConfigHandler('./config.ini').sync(template_config_variables)
在此调用之后,config.ini 文件在 config.ini.template 所在的同一目录中创建,应如下所示:
情景#2
现在阅读您新创建的 config.ini:
from config_handler import ConfigHandler
config = ConfigHandler('./config.ini').read()
print(config.sections())
# >>> ['app1', 'app2']
print(dict(config['DEFAULT']))
# >>> {'send_email': 'true', 'authenticate_user': 'true'}
print(dict(config['app1']))
# >>> {'send_email': 'false', 'line_height': '12', 'input_path': 'path/to/project/root/input/app1', 'authenticate_user': 'true'}
print(config['DEFAULT']['send_email'])
# >>> 'true'
print(config['app1']['front_page_title'])
# >>> 'Hello World!'
print(config.getboolean('DEFAULT', 'send_email'))
# >>> True
print(config.getboolean('app2', 'send_email'))
# >>> False
.read()ConfigParser从 python 的本机配置文件解析器库返回对象
场景#3
用户在 config.ini 文件中进行了一些更改:
开发人员在 config.ini.template 文件中进行了一些更改:
然后你需要再次运行同步:
import os
from config_handler import ConfigHandler
template_config_variables = {
'project_root_path': os.path.join('path', 'to', 'project', 'root')
}
ConfigHandler('./config.ini').sync(template_config_variables)
同步后,config.ini 文件应如下所示:
因此,用户更改或添加的内容保留在 config.ini 中。
config.ini.template 中添加的所有新内容也都添加到了 config.ini 中。
情景#4
您可以同时同步和阅读:
from config_handler import ConfigHandler
config = ConfigHandler('./config.ini').sync({...}).read()
...
异常处理
from config_handler import (ConfigHandler,
ConfigHandlerException,
ConfigHandlerFileReadException)
try:
config = ConfigHandler('./config.ini').sync({...}).read()
except ConfigHandlerFileReadException:
"""Read exceptions"""
except ConfigHandlerException:
"""All Config Handler exceptions"""
项目详情
关
Config_Handler -0.1.0-py3-none-any.whl 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 6dd3ad8c27180a3267fd597bd7324b9b85bd9e2b76e390483ed348b346a403ec |
|
| MD5 | 7a2d6b5ae788ba798adead8cdb076c0c |
|
| 布莱克2-256 | 7a4958812841be303a8006cdacd8306ef3bbf0af9c56bcd7e2a648baec339ac0 |