api / app /main.py
hanbinsite's picture
feat: complete core feature improvements
bf34e9d
Raw History Blame Contribute Delete
2 kB
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from app.cache import get_redis, close_redis
from app.config import settings
from app.limiter import limiter
from app.routers import admin_router
from app.routers.user import user_router
from app.services.scheduler import start_scheduler, stop_scheduler
@asynccontextmanager
async def lifespan(app: FastAPI):
# 初始化 Redis 连接(失败会自动降级,不阻断启动)
await get_redis()
start_scheduler()
yield
stop_scheduler()
await close_redis()
app = FastAPI(
title="BinV API",
description="影视资源聚合API服务",
version="0.1.0",
lifespan=lifespan,
)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(
CORSMiddleware,
allow_origins=[o.strip() for o in settings.CORS_ORIGINS.split(",")],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(admin_router, prefix="/admin")
app.include_router(user_router, prefix="/user")
@app.get("/health")
async def health_check():
from sqlalchemy import text
from app.database import async_session
from app.cache import get_redis
# 数据库检查
try:
async with async_session() as db:
await db.execute(text("SELECT 1"))
db_status = "ok"
except Exception as e:
db_status = f"error: {e}"
# Redis 检查
try:
r = await get_redis()
if r:
await r.ping()
redis_status = "ok"
else:
redis_status = "disabled"
except Exception as e:
redis_status = f"error: {e}"
overall = "ok" if db_status == "ok" else "degraded"
return {
"status": overall,
"db": db_status,
"redis": redis_status,
}