main.py 2.5 KB

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