From f4b40e7ff3fe2a73282741366ff06e31da1ee054 Mon Sep 17 00:00:00 2001 From: liangtianyu <124244236@qq.com> Date: Wed, 3 Dec 2025 10:24:55 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=8E=A5=E5=8F=A3=E6=96=87?= =?UTF-8?q?=E6=A1=A3=E7=A6=81=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/config.py | 13 +++++++------ main.py | 40 +++++++++++++++++++++++++--------------- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/app/config.py b/app/config.py index 704f91c..e3c1953 100644 --- a/app/config.py +++ b/app/config.py @@ -4,19 +4,19 @@ from pydantic_settings import BaseSettings class Settings(BaseSettings): # 数据库配置 database_url: str = "" - + # Redis配置 redis_url: str = "redis://localhost:6379/0" redis_lock_timeout: int = 30 # 锁超时时间(秒) redis_lock_retry_delay: float = 0.1 # 锁重试延迟(秒) redis_lock_max_retries: int = 100 # 最大重试次数 - + # 业务配置 count_threshold: int = 3 # count阈值,大于等于此值直接返回 external_api_enabled: bool = False # 是否启用外部API调用 external_api_retry_max: int = 3 # 外部API最大重试次数 external_api_url: str = "" - + # 日志配置 log_level: str = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL log_file: str = "logs/app.log" # 日志文件路径 @@ -24,15 +24,16 @@ class Settings(BaseSettings): log_backup_count: int = 5 # 备份文件数量 log_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" log_date_format: str = "%Y-%m-%d %H:%M:%S" - + # 应用配置 app_name: str = "AI Talk Callback API" environment: str = "production" # 环境: production, test, development debug: bool = False - + disable_docs: bool = False + class Config: env_file = ".env" case_sensitive = False -settings = Settings() \ No newline at end of file +settings = Settings() diff --git a/main.py b/main.py index a693e3d..4fef284 100644 --- a/main.py +++ b/main.py @@ -13,29 +13,30 @@ from app.logger import get_logger, LoggerManager LoggerManager.setup_logging() logger = get_logger("main") + @asynccontextmanager async def lifespan(app: FastAPI): # 启动时初始化 logger.info("🚀 应用启动中...") - + try: # 初始化数据库 logger.info("📊 初始化数据库连接...") await init_db() logger.info("✅ 数据库连接成功") - + # 初始化Redis logger.info("🔴 初始化Redis连接...") await redis_manager.connect() logger.info("✅ Redis连接成功") - + logger.info(f"🎉 {settings.app_name} 启动完成!") yield - + except Exception as e: logger.error(f"❌ 应用启动失败: {e}") raise - + finally: # 关闭时清理 logger.info("🛑 应用关闭中...") @@ -44,14 +45,25 @@ async def lifespan(app: FastAPI): logger.info("✅ Redis连接已关闭") except Exception as e: logger.error(f"❌ Redis关闭时出错: {e}") - + logger.info("👋 应用已关闭") app = FastAPI( title=settings.app_name, version="1.0.0", - lifespan=lifespan + lifespan=lifespan, + docs_url=( + "/docs" + if not settings.disable_docs and settings.environment != "production" + else None + ), + redoc_url=( + "/redoc" + if not settings.disable_docs and settings.environment != "production" + else None + ), + openapi_url="/openapi.json" if not settings.disable_docs else None, ) # 添加CORS中间件 @@ -73,8 +85,9 @@ async def root(): if settings.environment == "production": logger.warning("🚫 生产环境下禁止访问根接口") from fastapi import HTTPException + raise HTTPException(status_code=404, detail="Not Found") - + logger.info("📝 根接口被访问") return {"message": f"Welcome to {settings.app_name}"} @@ -85,17 +98,14 @@ async def health_check(): if settings.environment == "production": logger.warning("🚫 生产环境下禁止访问健康检查接口") from fastapi import HTTPException + raise HTTPException(status_code=404, detail="Not Found") - + logger.debug("💓 健康检查接口被访问") return {"status": "healthy"} if __name__ == "__main__": import uvicorn - uvicorn.run( - "main:app", - host="0.0.0.0", - port=8000, - reload=settings.debug - ) \ No newline at end of file + + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=settings.debug)