python基础之ConfigParser配置参数,背景、示例、方法
dynaconf
-
目录结构
settings ├── __init__.py ├── constant.py ├── setting.py ├── settings.dev.toml └── settings.production.toml
-
setting.py
import os from dynaconf import Dynaconfsettings_dir = os.path.dirname(os.path.abspath(__file__)) config = Dynaconf(env=os.environ.get("ENVIRONMENT") or "development",settings_files=[os.path.join(settings_dir, "settings.setting.toml"), # 开发、生产环境公用配置os.path.join(settings_dir, "settings.dev.toml"), # 开发环境os.path.join(settings_dir, "settings.production.toml"), # 生产环境],environments=True, # 是否使用多环境 )
-
settings.setting.toml
[default] port = 8080
-
settings.dev.toml
[development] DB_HOST='127.0.0.1' DB_PORT=6379 DB_USER='document_dev' DB_PASSWD= '123456'
-
settings.production.toml
[production] DB_HOST='127.0.0.1' DB_PORT=6379 DB_USER='document_prod' DB_PASSWD= '123456'
-
如何引用
db_host = config.DB_HOST
toml 文件中小写,也要改成引用时也该改成大写
ENVIRONMENT=production uvicorn main:app --reload ENVIRONMENT=dev uvicorn main:app --host 0.0.0.0 --port 8083 --reload