python从环境变量和配置文件中获取配置参数

前言

从环境变量和配置文件中获取配置参数,相关库:

  • python-dotenv:第三方库,需要使用pip安装
  • configparser:标准库

代码

  • test.ini

    [mysql]
    host = "192.168.0.10"
    port = 3306
    user = "root"
    password = "123456"
    [postgresql]
    host = "192.168.0.11"
    port = 5432
    user = "postgres"
    password = "123456"

  • demo.py

    from configparser import ConfigParser, NoSectionError, NoOptionError
    from dotenv import load_dotenv
    import os

    如果存在环境变量的文件,则加载配置到环境变量

    if os.path.exists("settings.env"):
    load_dotenv("settings.env")
    os_env = os.environ
    def read_config(filename: str) -> ConfigParser:
    """
    从文件中读取配置信息
    Parameters
    ----------
    filename : str, 配置文件
    """
    # 实例化对象
    config = ConfigParser()
    if not os.path.exists(filename):
    raise FileNotFoundError(f"配置文件 {filename} 不存在")
    config.read(filename, encoding="utf-8")
    return config
    def get_config(config: ConfigParser, section: str, key: str):
    """
    根据指定section和key获取value
    Parameters
    ----------
    config: ConfigParser(), 配置实例对象
    section: str, 配置文件中的区域
    key: str, 配置的参数名
    """
    # 优先从环境变量中获取配置参数, 没有的话再从配置文件中获取
    value = os_env.get(key, "")
    if not value:
    try:
    value = config.get(section, key)
    except (NoOptionError, NoSectionError):
    # 没有的话就返回None
    value = None
    return value
    if name == 'main':
    config = read_config("test.ini")
    print(get_config(config, "mysql", "host"))

相关推荐
Scott9999HH2 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
码智社3 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海3 小时前
python 列表、元组、集合和字典
开发语言·python
二十雨辰3 小时前
[爬虫]-Urllib
爬虫·python
萧瑟余晖4 小时前
JDK 26 新特性详解
java·开发语言
马优晨4 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
玉鸯5 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_446260856 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest