Dynaconf模块——python项目的配置管理
介绍
dyanconf是OSM(Object Settings Mapper), 能够从不同的配置数据存储方式中读取配置,例如python配置文件、系统环境变量、redis、ini文件、json文件等等。
使用参考链接:
示例代码
import os
import sys
from pathlib import Path
from dynaconf import Dynaconf
_BASE_DIR = Path(__file__).parent.parent
_CONFIG_DIR = _BASE_DIR / 'config'
LOG_DIR = _BASE_DIR / 'files' / 'logs'
TOKEN_FILE = _BASE_DIR / 'config' / 'xxl_job.token'
SHELVEDB_FILE = _BASE_DIR / 'DB' / 'SHELVE'
settings_files = [
_CONFIG_DIR / 'settings.toml',
_CONFIG_DIR / '.secrets.toml',
] # 指定加载默认配置的绝对路径
settings = Dynaconf(
envvar_prefix="CRM", # 环境变量前缀。设置`MSP_FOO='bar'`,使用`settings.FOO`
settings_files=settings_files,
environments=False, # 启用多层次日志,支持 dev, pro
load_dotenv=True, # 加载 .env
env_switcher="MSP_ENV", # 用于切换模式的环境变量名称 MSP_ENV=production
lowercase_read=True, # 禁用小写访问, settings.name 是不允许的
includes=[os.path.join(sys.prefix, 'settings.toml')], # 自定义配置覆盖默认配置
base_dir=_BASE_DIR, # 编码传入配置
)
使用方法
安装, 使用pip
pip install dynaconf
初始化, 项目的根目录中运行 dynaconf init 命令
dynaconf init -f toml输出如下⚙️ Configuring your Dynaconf environment ------------------------------------------ The file `config.py` was generated. ️ settings.toml created to hold your settings. .secrets.toml created to hold your secrets. the .secrets.* is also included in `.gitignore` beware to not push your secrets to a public repo. Dynaconf is configured! read more on https://dynaconf.com- 生成如下文件
. ├── config.py # 需要被导入的配置脚本 ├── .secrets.toml # 像密码等敏感信息配置 └── settings.toml # 应用配置 - 在settings.toml文件中编写配置
[DATABASE.CONFIG.MSP] DRIVER='mysql+pymysql' USER='my_user'
已有项目不使用init
- 新建config文件夹
- 新建__init__.py文件,编写示例代码
- 在config文件夹下新建settings.toml文件和secrets.toml文件
- 其他要使用的模块中导入
from config import settings
如何使用
直接使用settings.DATABASE.CONFIG.MSP.DRIVER样式即可调用
posted on 2024-01-29 15:35 ishuangjin 阅读(917) 评论(0) 收藏 举报
浙公网安备 33010602011771号