This commit is contained in:
DengDai
2025-12-08 14:47:24 +08:00
commit 644b5aaaf8
21 changed files with 1543 additions and 0 deletions

50
pt_gen/core/config.py Normal file
View File

@@ -0,0 +1,50 @@
import yaml
from functools import lru_cache
from pydantic import BaseModel
from pydantic_settings import BaseSettings
from typing import Optional
CONFIG_PATH = "configs/config.yaml"
class TMDBConfig(BaseModel):
api_key: Optional[str] = None
class DoubanConfig(BaseModel):
cookie: Optional[str] = None
class RedisConfig(BaseModel):
host: str
port: int
db: int
cache_ttl_seconds: int
class UploaderConfig(BaseModel):
enable: bool
api_url: str
api_key: str
class Settings(BaseSettings):
api_key: str
tmdb: TMDBConfig
douban: DoubanConfig
redis: RedisConfig
uploader: UploaderConfig
def set_config_path(path: str = "configs/config.yaml"):
"""允许在启动时设置配置文件路径"""
global CONFIG_PATH
CONFIG_PATH = path
@lru_cache() # 使用 lru_cache 确保配置文件只被读取和解析一次
def get_settings() -> Settings:
"""
加载并返回配置对象。
这是一个可被 FastAPI 依赖注入的函数。
"""
try:
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
config_data = yaml.safe_load(f)
return Settings.parse_obj(config_data)
except FileNotFoundError:
raise RuntimeError(f"配置文件未找到: {CONFIG_PATH}")
except Exception as e:
raise RuntimeError(f"加载配置文件失败: {e}")