File size: 2,004 Bytes
32ddb29 bf34e9d 32ddb29 bf34e9d 32ddb29 bf34e9d 9d66536 32ddb29 bf34e9d 9d66536 32ddb29 9d66536 bf34e9d 32ddb29 bf34e9d 32ddb29 bf34e9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | 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,
}
|