FastAPI异步startup函数实例化大模型并跨模块导入的优化方案
方案1:使用FastAPI内置的
app.state存储(官方推荐首选) FastAPI 实例自带state属性,专门用来存放应用生命周期内的全局共享对象,完全不需要用全局变量。
首先修改main.py的启动逻辑:
from fastapi import FastAPI from src.router import api_router from big_model_loader import load_big_model app = FastAPI() app.include_router(api_router, prefix='/api') @app.on_event("startup") async def startup_event(): await init_middlewares(app) # 直接把模型挂载到app.state上 app.state.big_model = load_big_model('filename')
在mymodule.py的路由函数里可以直接通过Request对象取实例:
from fastapi import Request, APIRouter router = APIRouter() @router.get("/test-model") async def test_model(request: Request): # 直接从request.app.state里拿模型实例 model = request.app.state.big_model # 调用模型逻辑 res = model.predict(xxx) return {"result": res}
方案2:封装单例模式的模型加载工具
如果不想和FastAPI的实例耦合,可以自己写一个单例的模型加载模块,保证不管在哪里导入调用,都只会加载一次模型。
首先新建src/utils/model_loader.py文件:
from big_model_loader import load_big_model from typing import Optional # 模块级别的变量本身就是单例 _big_model: Optional[object] = None def get_big_model() -> object: global _big_model if _big_model is None: _big_model = load_big_model('filename') return _big_model
然后在main.py的启动事件里预加载:
@app.on_event("startup") async def startup_event(): await init_middlewares(app) # 启动时预加载模型 from src.utils.model_loader import get_big_model get_big_model()
在mymodule.py里直接导入调用即可:
from src.utils.model_loader import get_big_model @router.get("/test-model") async def test_model(): model = get_big_model() res = model.predict(xxx) return {"result": res}
这个方案的好处是完全和FastAPI解耦,后续更换框架也可以复用加载逻辑。
方案3:用FastAPI依赖注入实现
你也可以把模型封装成一个全局依赖,启动时初始化,路由里直接注入使用,更符合FastAPI的设计风格:
首先定义依赖文件src/deps.py:
from fastapi import Request async def get_big_model(request: Request): return request.app.state.big_model
然后在路由里直接注入:
# mymodule.py from src.deps import get_big_model from fastapi import Depends @router.get("/test-model") async def test_model(model = Depends(get_big_model)): res = model.predict(xxx) return {"result": res}
三种方案都不会有全局变量污染的问题,维护性远高于直接用global变量,优先选择第一种官方推荐方案即可。
内容的提问来源于stack exchange,提问作者Lele Canfora
相关产品推荐
相关产品推荐

