Skip to content

修复 database_config 加载环境变量路径错误问题 (target: learn_version)#101

Open
Zi-Lan-Cui wants to merge 1 commit into
jjyaoao:learn_versionfrom
Zi-Lan-Cui:learn_version
Open

修复 database_config 加载环境变量路径错误问题 (target: learn_version)#101
Zi-Lan-Cui wants to merge 1 commit into
jjyaoao:learn_versionfrom
Zi-Lan-Cui:learn_version

Conversation

@Zi-Lan-Cui

Copy link
Copy Markdown

问题

当前的修复版本依赖每次用户手动在文件最开始手动加载

from dotenv import load_dotenv
load_dotenv()

这种方式不太方便。实际上 dotenv 提供了修改默认 env 位置的方法 find_dotenv( ),该方法在 load_dotenv 注释中被官方提及

"""
    If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the
    .env file with it's default parameters. If you need to change the default parameters
    of `find_dotenv()`, you can explicitly call `find_dotenv()` and pass the result
    to this function as `dotenv_path`.
"""

def find_dotenv(
    filename: str = ".env",
    raise_error_if_not_found: bool = False,
    usecwd: bool = False,
) -> str:
    """
    Search in increasingly higher folders for the given file

    Returns path to the file if found, or an empty string otherwise
    """

只需要设置usecwd=True即可实现自动加载工作目录同级的.env文件。该方案更加优雅且通用。

修复

使用 dotenv 官方推荐的 find_dotenv(usecwd=True) 从当前工作目录向上查找 .env 文件,替代无参 load_dotenv()。该方案:

  • 无需用户手动进行环境变量加载
  • 适配任意 CWD(只要在 .env 所在目录或其子目录运行)
  • 是 dotenv 文档中明确推荐的用法

额外说明

该改动增强了现有的保底策略。如果想要用户完全不需手动加载。可以将semantic.py中的get_database_config导入提升到模块级。

def _init_databases(self):
        """初始化专业数据库存储"""
        try:
            # 需要放到正常头文件加载位置,否则用户未手动加载环境,前面的流程仍然可能报错
            from ...core.database_config import get_database_config
            # 获取数据库配置
            db_config = get_database_config()
            ...

该方案我已经在本地多次测试,运行无误。希望意见能被采纳

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant