main.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """FastAPI应用主入口"""
  2. import os
  3. from fastapi import FastAPI
  4. from fastapi.middleware.cors import CORSMiddleware
  5. from fastapi.responses import FileResponse
  6. from fastapi.staticfiles import StaticFiles
  7. from .config import settings
  8. from .utils.logging_setup import setup_logging
  9. setup_logging(settings.enable_file_logging)
  10. from .routers import config, document, outline, content, expand
  11. # 创建FastAPI应用实例
  12. app = FastAPI(
  13. title=settings.app_name,
  14. version=settings.app_version,
  15. description="基于FastAPI的AI写标书助手后端API",
  16. )
  17. # 添加CORS中间件
  18. app.add_middleware(
  19. CORSMiddleware,
  20. allow_origins=settings.cors_origins,
  21. allow_credentials=True,
  22. allow_methods=["*"],
  23. allow_headers=["*"],
  24. )
  25. # 注册路由
  26. app.include_router(config.router)
  27. app.include_router(document.router)
  28. app.include_router(outline.router)
  29. app.include_router(content.router)
  30. app.include_router(expand.router)
  31. # 健康检查端点
  32. @app.get("/health")
  33. async def health_check():
  34. """健康检查"""
  35. return {
  36. "status": "healthy",
  37. "app_name": settings.app_name,
  38. "version": settings.app_version,
  39. }
  40. # 静态文件服务(用于服务前端构建文件)
  41. if os.path.exists("static"):
  42. # 挂载静态资源文件夹
  43. app.mount("/static", StaticFiles(directory="static/static"), name="static")
  44. # 处理React应用的路由(SPA路由支持)
  45. @app.get("/")
  46. async def read_index():
  47. """根路径,返回前端首页"""
  48. return FileResponse("static/index.html")
  49. @app.get("/{full_path:path}")
  50. async def serve_react_app(full_path: str):
  51. """处理React路由,所有非API路径都返回index.html"""
  52. # 排除API路径
  53. if (
  54. full_path.startswith("api/")
  55. or full_path.startswith("docs")
  56. or full_path.startswith("health")
  57. ):
  58. # 这些路径应该由FastAPI处理,如果到这里说明404
  59. from fastapi import HTTPException
  60. raise HTTPException(status_code=404, detail="接口不存在")
  61. # 检查是否是静态文件
  62. static_file_path = os.path.join("static", full_path)
  63. if os.path.exists(static_file_path) and os.path.isfile(static_file_path):
  64. return FileResponse(static_file_path)
  65. # 对于其他所有路径,返回React应用的index.html(SPA路由)
  66. return FileResponse("static/index.html")
  67. else:
  68. # 如果没有静态文件,返回API信息
  69. @app.get("/")
  70. async def read_root():
  71. """根路径,返回API信息"""
  72. return {
  73. "message": f"欢迎使用 {settings.app_name} API",
  74. "version": settings.app_version,
  75. "docs": "/docs",
  76. "health": "/health",
  77. }