Dynaconf模块——python项目的配置管理

介绍

dyanconf是OSM(Object Settings Mapper), 能够从不同的配置数据存储方式中读取配置,例如python配置文件、系统环境变量、redis、ini文件、json文件等等。
使用参考链接:

  1. https://pypi.org/project/dynaconf/
  2. https://www.dynaconf.com/

示例代码

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 命令

  1. 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
  2. 生成如下文件
    .
    ├── config.py # 需要被导入的配置脚本
    ├── .secrets.toml # 像密码等敏感信息配置
    └── settings.toml # 应用配置
  3. 在settings.toml文件中编写配置
    [DATABASE.CONFIG.MSP]
    DRIVER='mysql+pymysql'
    USER='my_user'

已有项目不使用init

  1. 新建config文件夹
  2. 新建__init__.py文件,编写示例代码
  3. 在config文件夹下新建settings.toml文件和secrets.toml文件
  4. 其他要使用的模块中导入 from config import settings

如何使用

直接使用settings.DATABASE.CONFIG.MSP.DRIVER样式即可调用

posted on   ishuangjin  阅读(550)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

点击右上角即可分享
微信分享提示