58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
import uvicorn
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from database import init_db, engine
|
|
from config import settings
|
|
from routers import templates, models, generate, export
|
|
from services.minio_client import init_buckets
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
await init_db()
|
|
await init_buckets() # 初始化 MinIO 存储桶
|
|
yield
|
|
await engine.dispose()
|
|
|
|
|
|
app = FastAPI(title=settings.APP_NAME, version=settings.APP_VERSION, lifespan=lifespan)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
app.include_router(templates.router, prefix="/api/v1/templates", tags=["模板管理"])
|
|
app.include_router(models.router, prefix="/api/v1/models", tags=["模型管理"])
|
|
app.include_router(generate.router, prefix="/api/v1/generate", tags=["生成管理"])
|
|
app.include_router(export.router, prefix="/api/v1/export", tags=["导出管理"])
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(_: Request, exc: HTTPException):
|
|
return JSONResponse(status_code=exc.status_code, content={"code": -1, "message": exc.detail})
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unhandled_exception_handler(_: Request, exc: Exception):
|
|
return JSONResponse(status_code=500, content={"code": -1, "message": str(exc) or "服务器内部错误"})
|
|
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {"code": 0, "data": {"name": settings.APP_NAME, "version": settings.APP_VERSION}, "message": "ok"}
|
|
|
|
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"code": 0, "data": {"status": "ok"}, "message": "ok"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run("main:app", host=settings.HOST, port=settings.PORT, reload=settings.DEBUG)
|