一、简介
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, # 编码传入配置
)
二、使用方法
2.1 安装
pip install dynaconf
2.2 使用
2.2.1 初始化, 项目的根目录中运行命令
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
2.2.2 生成如下文件
.
├── config.py # 需要被导入的配置脚本
├── .secrets.toml # 像密码等敏感信息配置
└── settings.toml # 应用配置
2.2.3 在settings.toml文件中编写配置
[DATABASE.CONFIG.MSP]
DRIVER='mysql+pymysql'
USER='my_user'
2.3 已有项目不使用init
- 新建config文件夹
- 新建init.py文件,编写示例代码
- 在config文件夹下新建settings.toml文件和secrets.toml文件
- 其他要使用的模块中导入 from config import settings
2.4 如何使用
直接使用
settings.DATABASE.CONFIG.MSP.DRIVER 样式即可调用
python 其它实用包
爬虫: http://www.lifefunker.com/archives/758