diff --git a/app/config/__init__.py b/app/config/__init__.py index 0c0b5ba..cfd082a 100644 --- a/app/config/__init__.py +++ b/app/config/__init__.py @@ -1,10 +1,13 @@ import os -from .settings import Settings +from .settings import BASE_DIR, Settings _env = os.getenv("ENV", "dev") _env_files = {"dev": ".env", "test": ".env.test", "pro": ".env.prod"} -settings = Settings(_env_file=_env_files.get(_env, ".env")) +# 使用基于项目根目录的绝对路径,避免受 PyCharm/命令行工作目录(CWD)影响 +_env_file = BASE_DIR / _env_files.get(_env, ".env") + +settings = Settings(_env_file=_env_file) __all__ = ["settings"] diff --git a/app/config/settings.py b/app/config/settings.py index 38e02c4..a54b21a 100644 --- a/app/config/settings.py +++ b/app/config/settings.py @@ -1,5 +1,10 @@ +from pathlib import Path + from pydantic_settings import BaseSettings, SettingsConfigDict +# 项目根目录:settings.py -> config -> app -> +BASE_DIR = Path(__file__).resolve().parents[2] + class Settings(BaseSettings): # 环境 @@ -71,7 +76,7 @@ class Settings(BaseSettings): return f"redis://{self.redis_host}:{self.redis_port}/{self.redis_db}" model_config = SettingsConfigDict( - env_file=".env", + env_file=BASE_DIR / ".env", env_file_encoding="utf-8", case_sensitive=False, extra="ignore",