Files
2026-04-10 10:34:41 +08:00

44 lines
1.1 KiB
Python

from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.core.logger import log
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理:初始化和释放所有连接资源"""
from app.core.database import init_db, close_db
from app.core.redis import RedisManager
from pathlib import Path
# 启动:初始化资源
try:
log.info("初始化数据库连接")
await init_db()
except Exception as e:
log.error(f"数据库连接初始化失败: {e}")
raise e
try:
log.info("初始化redis连接")
await RedisManager.init()
except Exception as e:
log.warning(f"Redis 连接初始化失败: {e}")
raise e
log.info("所有资源已初始化,应用启动完成")
# 打印 banner
banner_path = Path(__file__).parent.parent / "banner.txt"
if banner_path.exists():
print(banner_path.read_text(encoding="utf-8"))
yield
# 关闭:释放资源
await close_db()
await RedisManager.close()
log.info("所有连接资源已释放")