main.py 2.59 KB
"""FastAPI 应用入口"""
import logging
from pathlib import Path
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

from app.api import providers, accounts, strategies, prompts, calls, async_tasks, orchestration, adapter, auth, log_storage, word_bank, statistics
from app.core.config import settings

# 日志配置
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL),
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info(f"{settings.APP_NAME} v{settings.APP_VERSION} 启动中...")
    yield
    logger.info(f"{settings.APP_NAME} 已关闭")


app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    lifespan=lifespan,
)

# CORS 配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(providers.router)
app.include_router(accounts.router)
app.include_router(strategies.router)
app.include_router(prompts.router)
app.include_router(calls.router)
app.include_router(async_tasks.router)
app.include_router(orchestration.router)
app.include_router(adapter.router)
app.include_router(auth.router)
app.include_router(log_storage.router)
app.include_router(word_bank.router)
app.include_router(statistics.router)


# ---- 静态文件托管(前端 SPA) ----
FRONTEND_DIST = Path(__file__).resolve().parents[2] / "frontend" / "dist"
if FRONTEND_DIST.exists():
    logger.info(f"挂载前端静态文件: {FRONTEND_DIST}")
    app.mount("/assets", StaticFiles(directory=str(FRONTEND_DIST / "assets")), name="assets")

    @app.get("/{full_path:path}")
    async def serve_frontend(full_path: str):
        """为所有非 API 路由返回 index.html(SPA 支持)"""
        if full_path.startswith("api/"):
            from fastapi.responses import JSONResponse
            return JSONResponse(status_code=404, content={"detail": "Not Found"})
        index_file = FRONTEND_DIST / "index.html"
        if not index_file.exists():
            return JSONResponse(status_code=404, content={"detail": "Not Found"})
        return FileResponse(str(index_file))
else:
    logger.warning(f"前端静态文件目录不存在: {FRONTEND_DIST},请确保已编译前端或使用 npm run dev")

@app.get("/api/health")
async def health_check():
    return {"status": "ok", "version": settings.APP_VERSION}