python基础之dynaconf配置参数,背景、示例、方法(根据环境动态配置参数)

python基础之ConfigParser配置参数,背景、示例、方法

dynaconf
  • 目录结构

    cpp 复制代码
    settings
    ├── __init__.py
    ├── constant.py
    ├── setting.py
    ├── settings.dev.toml
    └── settings.production.toml
  • setting.py

    clike 复制代码
    import os
    from dynaconf import Dynaconf
    
    settings_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

    csharp 复制代码
    [development]
    DB_HOST='127.0.0.1'
    DB_PORT=6379
    DB_USER='document_dev'
    DB_PASSWD= '123456'
  • settings.production.toml

    csharp 复制代码
    [production]
    DB_HOST='127.0.0.1'
    DB_PORT=6379
    DB_USER='document_prod'
    DB_PASSWD= '123456'
  • 如何引用

    cpp 复制代码
     db_host = config.DB_HOST 
    复制代码
    toml 文件中小写,也要改成引用时也该改成大写
    cpp 复制代码
    ENVIRONMENT=production uvicorn main:app --reload
    ENVIRONMENT=dev uvicorn main:app --host 0.0.0.0 --port 8083 --reload
相关推荐
HarmonLTS9 分钟前
Python Socket网络通信详解
服务器·python·网络安全
郝学胜-神的一滴20 分钟前
Python数据封装与私有属性:保护你的数据安全
linux·服务器·开发语言·python·程序人生
智航GIS28 分钟前
11.7 使用Pandas 模块中describe()、groupby()进行简单分析
python·pandas
Pyeako32 分钟前
机器学习--矿物数据清洗(六种填充方法)
人工智能·python·随机森林·机器学习·pycharm·线性回归·数据清洗
ScilogyHunter1 小时前
SCons:Python驱动的智能构建系统
python·构建系统·scons
luoluoal1 小时前
基于python的基于深度学习的车俩特征分析系(源码+文档)
python·mysql·django·毕业设计·源码
轻竹办公PPT2 小时前
2026 年 AI 办公趋势:AI 生成 PPT 工具谁在领先
人工智能·python
Kingairy2 小时前
Python面试高频题
java·python·面试
黎雁·泠崖2 小时前
Java数组入门:定义+静态/动态初始化全解析(隐式转换+案例+避坑指南)
java·开发语言·python