main.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # 主应用入口,整合多个 FastAPI 应用
  2. import uvicorn
  3. from fastapi import FastAPI
  4. from contextlib import asynccontextmanager
  5. # 导入所有子应用
  6. from api.search_infinity import app as search_app
  7. # 定义主应用的生命周期管理
  8. @asynccontextmanager
  9. async def main_lifespan(app: FastAPI):
  10. """主应用生命周期管理"""
  11. from utils.infinity import get_client, close_client
  12. print("=== Infinity API Gateway 启动 ===")
  13. # 1. 初始化全局客户端(在服务启动时)
  14. get_client(database="book_image_db")
  15. print("✅ Infinity客户端已初始化")
  16. yield
  17. print("=== Infinity API Gateway 关闭 ===")
  18. # 2. 关闭全局客户端(在服务关闭时)
  19. close_client()
  20. print("✅ Infinity客户端已关闭")
  21. # 创建主应用
  22. main_app = FastAPI(
  23. title="Infinity API Gateway",
  24. description="整合多个 FastAPI 应用的 API 网关",
  25. version="1.0.0",
  26. lifespan=main_lifespan
  27. )
  28. # 挂载子应用
  29. # 1. 搜索 API - 访问路径: /search/*
  30. main_app.mount("/search", search_app, name="search_api")
  31. # 主应用根路径
  32. @main_app.get("/")
  33. async def root():
  34. """API 网关根路径"""
  35. return {
  36. "message": "Welcome to GRAPH_RAG API Gateway",
  37. "available_apps": {
  38. "search_api": "访问路径: /search, 文档: /search/docs",
  39. "hybrid_http_api": "访问路径: /hybrid, 文档: /hybrid/docs"
  40. }
  41. }
  42. # 健康检查端点
  43. @main_app.get("/health")
  44. async def health_check():
  45. """主应用健康检查"""
  46. return {"status": "healthy", "service": "Infinity API Gateway"}
  47. if __name__ == "__main__":
  48. """启动主应用"""
  49. uvicorn.run(
  50. "main:main_app", # 应用路径: 模块名:应用实例名
  51. host="0.0.0.0", # 允许所有IP访问
  52. port=18001, # 服务端口
  53. reload=False, # 开发模式下自动重载
  54. workers=1, # 生产环境可根据需要增加
  55. log_level="info" # 日志级别
  56. )