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
相关推荐
Csvn21 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch891821 小时前
Python主流框架全解析
开发语言·python
sg_knight21 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财1 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz1 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据1 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby1 天前
springboot读取配置文件
后端·python·flask
阿Y加油吧1 天前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python