main.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import asyncio
  2. import os
  3. import threading
  4. from contextlib import asynccontextmanager
  5. from fastapi import FastAPI
  6. from fastapi.middleware.cors import CORSMiddleware
  7. # 导入配置
  8. from core.config import logger
  9. # 导入API路由
  10. from api.search import router as search_router
  11. from api.health import router as health_router
  12. # 创建 FastAPI 应用
  13. app = FastAPI(
  14. title="RAG",
  15. description="RAG数据检索",
  16. version="1.0.0"
  17. )
  18. # 添加 CORS 中间件
  19. app.add_middleware(
  20. CORSMiddleware,
  21. allow_origins=["*"],
  22. allow_credentials=True,
  23. allow_methods=["*"],
  24. allow_headers=["*"],
  25. )
  26. # 注册路由
  27. app.include_router(health_router, tags=["健康检查"])
  28. app.include_router(search_router, tags=["数据检索"])
  29. # 定义生命周期事件处理器
  30. @asynccontextmanager
  31. async def lifespan(app: FastAPI):
  32. # Startup 逻辑
  33. print("正在启动数据胶囊 API 服务...")
  34. # 初始化一些资源,例如数据库连接
  35. # app.state.db = await init_database() # 假设是异步初始化
  36. yield # 应用在此处运行,处理请求
  37. # Shutdown 逻辑
  38. print("数据胶囊 API 服务正在关闭...")
  39. if __name__ == "__main__":
  40. import uvicorn
  41. os.environ['RAG_ENV'] = 'prod'
  42. uvicorn.run(app, host="0.0.0.0", port=5000)