当前位置: 首页 > news >正文

FastAPI 托管前端静态文件

将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)

 

http://www.jsqmd.com/news/782251/

相关文章:

  • 京牌指标获取的价格,中诚卓越在多地合理吗? - mypinpai
  • ESP芯片烧录终极指南:5个esptool高效使用技巧
  • ceshi02ceshi02ceshi02ceshi02ceshi02ceshi02
  • 服务网络盘点:覆盖售前售后的日本二手机床知名服务商 - 品牌推荐大师
  • OpenClaw凭证保险库:为多用户AI助手构建安全的API密钥管理中间件
  • 哈尔滨香坊区商务会议酒店排行:5家优选场地盘点 - 奔跑123
  • 一个来自c++学生的吐槽
  • Docker化部署OpenClaw爬虫:一键解决环境依赖与跨平台运行难题
  • AI技能管理框架设计:从标准化接口到动态编排实践
  • Vivado 2019.2 联合 ModelSim 2019.2 仿真,我踩过的那些坑(附完整避坑指南)
  • 深圳诚信驾培标杆|宝华驾校获市监局认证、724客服、首创智驾陪驾体系完全指南 - 优质企业观察收录
  • NVIDIA GeForce NOW数据泄露全链路复盘:ShinyHunters击穿第三方防线,云游戏供应链安全体系全面崩塌
  • 国内精巧型压力变送器十大品牌排名 - 仪表人小余
  • 2026年无溶剂环氧涂料优质厂家推荐指南 廊坊佐涂防腐设备有限公司优选 无溶剂环氧涂料/无溶剂环氧陶瓷涂料/无溶剂环氧液体涂料/环氧无溶剂防腐漆/厚浆型环氧防腐涂料 - 奔跑123
  • 2026实测:7款降AI率工具测评,论文AI率86%→12%,哪家最稳? - 降AI实验室
  • XHS-Downloader:小红书内容采集系统的架构设计与工程实践
  • 在Ubuntu 20.04上,用RTX 3090从零部署CUDA-BEVFusion(含TensorRT 8.5.2.2避坑指南)
  • 认知神经科学研究报告【20260036】
  • 强化学习与扩散模型在机器人运动生成中的应用
  • 2026年深圳C1/C2驾照直营培训避坑指南|宝华驾校纯直营零套路45天快速拿证 - 优质企业观察收录
  • 2026年氯化橡胶面漆优质厂家推荐指南 廊坊佐涂防腐设备有限公司优选 氯化橡胶面漆/氯化橡胶漆/氯化橡胶防腐面漆/船舶专用氯化橡胶面漆/耐海水氯化橡胶涂料 - 奔跑123
  • 多网格方法在Stokes方程求解中的GPU优化实践
  • GraphQL与大语言模型融合:gqlpt项目架构与生产实践指南
  • 从命令行小白到自动化大神:用Python argparse给你的脚本加上“智能”参数
  • 南充黄金回收哪家靠谱?9 区县全覆盖,6 大品牌免费上门,高价秒结无套路 - 金掌柜黄金回收
  • 树莓派摄像头除了监控还能干啥?用rpicam-apps玩转5个创意小项目(含代码)
  • 哈尔滨香坊区中高端酒店餐饮服务实力排行 - 奔跑123
  • 10分钟打造私人游戏云:Sunshine开源游戏串流服务器完整指南
  • 从gitee下载仓库
  • 抖音无水印批量下载工具深度解析与实战指南