57 lines
1.1 KiB
Python
57 lines
1.1 KiB
Python
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from contextlib import asynccontextmanager
|
|
|
|
from app.config import settings
|
|
from app.database import init_db
|
|
from app.redis_lock import redis_manager
|
|
from app.routes import router
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
# 启动时初始化
|
|
await init_db()
|
|
await redis_manager.connect()
|
|
yield
|
|
# 关闭时清理
|
|
await redis_manager.disconnect()
|
|
|
|
|
|
app = FastAPI(
|
|
title=settings.app_name,
|
|
version="1.0.0",
|
|
lifespan=lifespan
|
|
)
|
|
|
|
# 添加CORS中间件
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 注册路由
|
|
app.include_router(router)
|
|
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {"message": f"Welcome to {settings.app_name}"}
|
|
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
return {"status": "healthy"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(
|
|
"main:app",
|
|
host="0.0.0.0",
|
|
port=8000,
|
|
reload=settings.debug
|
|
) |