from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from algo.algo_runner_manager import get_algo_runner from apis.router import router import uvicorn import logging from common.biz_exception import BizExceptionHandlers from common.global_logger import logger app = FastAPI() # # 初始化 AlgoRunner # algo_runner = AlgoRunner() # # # # 使用 FastAPI 的 startup 事件来启动 AlgoRunner # @app.on_event("startup") # async def startup_event(): # algo_runner.start() algo_runner = get_algo_runner() @asynccontextmanager async def lifespan(app: FastAPI): # 应用启动时的初始化 algo_runner.start() # 允许请求处理 yield # 应用关闭时的清理逻辑 logger.info("Shutting down application...") # 包含所有模块的路由 app.include_router(router, prefix="/api") app.add_exception_handler(HTTPException, BizExceptionHandlers.biz_exception_handler) app.router.lifespan_context = lifespan if __name__ == "__main__": # 重定向 uvicorn 的日志 uvicorn_logger = logging.getLogger("uvicorn") uvicorn_logger.handlers = logger.handlers uvicorn_logger.setLevel(logging.DEBUG) # 重定向 uvicorn 的 access 日志 # access_logger = logging.getLogger("uvicorn.access") # access_logger.handlers = logger.handlers # access_logger.setLevel(logging.DEBUG) uvicorn.run(app, host="0.0.0.0", port=9000, log_config=None)