You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.6 KiB
61 lines
1.6 KiB
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI
|
|
from tortoise import Tortoise
|
|
from redis.asyncio import Redis
|
|
|
|
from app.core.exceptions import SettingNotFound
|
|
from app.core.init_app import (
|
|
init_data,
|
|
make_middlewares,
|
|
register_exceptions,
|
|
register_routers,
|
|
)
|
|
|
|
try:
|
|
from app.settings.config import settings
|
|
except ImportError:
|
|
raise SettingNotFound("Can not import settings")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
try:
|
|
# 初始化 Redis 连接
|
|
app.state.redis_client = Redis(
|
|
host=settings.REDIS_HOST,
|
|
port=settings.REDIS_PORT,
|
|
db=settings.REDIS_DB,
|
|
decode_responses=True,
|
|
password=settings.REDIS_PASSWORD
|
|
)
|
|
# 测试 Redis 连接
|
|
await app.state.redis_client.ping()
|
|
print("✅ Redis 连接成功")
|
|
except Exception as e:
|
|
print(f"❌ Redis 连接失败: {e}")
|
|
# 执行其他初始化操作
|
|
await init_data()
|
|
yield
|
|
# 关闭 Redis 连接
|
|
if hasattr(app.state, 'redis_client'):
|
|
await app.state.redis_client.close()
|
|
print("🛑 Redis 连接关闭")
|
|
# 关闭 Tortoise 连接
|
|
await Tortoise.close_connections()
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
app = FastAPI(
|
|
title=settings.APP_TITLE,
|
|
description=settings.APP_DESCRIPTION,
|
|
version=settings.VERSION,
|
|
openapi_url="/openapi.json",
|
|
middleware=make_middlewares(),
|
|
lifespan=lifespan,
|
|
)
|
|
register_exceptions(app)
|
|
register_routers(app, prefix="/api")
|
|
return app
|
|
|
|
|
|
app = create_app() |