将VUE3编译的静态文件放在backend/static下,并修改后端主程序启动类
main.py
import uvicorn
import logging
from pathlib import Path# 配置日志
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S'
)from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from app.database.db import engine, Base
from app.api.user import router as user_router
from app.api.datasource import router as datasource_router
from app.api.datasource_table import router as datasource_table_router
from app.api.multi_agent import router as multi_agent_router
from app.api.conversation import router as conversation_router
from app.api.summary_prompt import router as summary_prompt_router# 创建数据库表
Base.metadata.create_all(bind=engine)app = FastAPI()# 配置CORS
app.add_middleware(CORSMiddleware,allow_origins=["http://localhost:5173", "http://localhost:5174"], # 允许两个可能的前端域名allow_credentials=True,allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],allow_headers=["Content-Type", "Authorization"],
)# 注册路由
app.include_router(user_router)
app.include_router(datasource_router)
app.include_router(datasource_table_router)
app.include_router(multi_agent_router)
app.include_router(conversation_router)
app.include_router(summary_prompt_router)# 配置静态文件目录
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"# 检查静态文件目录是否存在,决定是否启用集成模式
if STATIC_DIR.exists() and (STATIC_DIR / "index.html").exists():logging.info("Static files detected - running in integrated mode (API + Frontend)")# 挂载静态文件app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")# 根路径和其他非API路径返回index.html(SPA支持)@app.get("/{full_path:path}")async def serve_spa(full_path: str):# 先检查是否是静态文件请求static_file_path = STATIC_DIR / full_pathif static_file_path.exists() and static_file_path.is_file():return FileResponse(str(static_file_path))# 否则返回 index.html 给 SPAindex_path = STATIC_DIR / "index.html"if index_path.exists():return FileResponse(str(index_path))return {"message": "Welcome to SQL Copilot API"}
else:logging.info("No static files found - running in backend-only mode (API only)")# 根路径@app.get("/")async def root():return {"message": "Welcome to SQL Copilot API"}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8000)
