介绍
dyanconf是OSM(Object Settings Mapper), 能够从不同的配置数据存储方式中读取配置,例如python配置文件、系统环境变量、redis、ini文件、json文件等。
参考链接:
https://pypi.org/project/dynaconf/
https://www.dynaconf.com/
安装
pip install dynaconf
初始化
cd path/to/your/project/
dynaconf init -f toml
编写配置文件
# 在settings.toml 或 .secrets.toml 里编写项目配置
a = "hi"
[local]
url = "setingdxxx"
使用配置数据
config.py中:
from dynaconf import Dynaconf
settings = Dynaconf(
envvar_prefix="DYNACONF",
settings_files=['settings.toml','.secrets.toml'],
)
mian.py中:
from config.config import settings
print(settings.local.url)
print(settings.a)
输出:
setingdxxx
hi
动态加载不同的配置
根据项目定义toml文件
可以在项目中定义自己想要的 toml 文件,并且定义文件位置
[test]
url = "testxxxxx"
[online]
url = "onlinexxxxx"
更新 config.py
from dynaconf import Dynaconf
settings = Dynaconf(
envvar_prefix="DYNACONF",
settings_files=['settings.toml', 'test.toml', 'online.toml', '.secrets.toml'],
environments=True # 可以根据环境变量来加载项目配置
)
设置环境变量加载项目配置
直接在程序里配置
mian.py中:
from config.config import settings
import os
# 设置环境变量,加载项目配置,直接在程序里配置
# 加载test环境
os.environ['ENV_FOR_DYNACONF'] = 'test'
print(settings.url)
输出:
testxxxxx