补充Depends 和 request: Request 依赖注入用法的注意事项

不要在非路由函数(如类的 __init__ 方法或普通模块函数)中直接使用 Depends() 或 request。
Depends 和 request: Request 是 FastAPI 提供的依赖注入机制的一部分,仅适用于FastAPI 路由函数 或由 FastAPI 调用的依赖函数中。在类初始化、模块级代码、启动事件等 FastAPI 注入上下文之外使用,会导致错误或行为异常。


📌 补充解释:

场景 是否能使用 Depends() 或 request: Request 说明
路由函数中 ✅ 可以 FastAPI 自动注入
依赖函数中 ✅ 可以 由 FastAPI 调用,注入上下文有效
类 __init__ 构造函数中 ❌ 不可以 FastAPI 不会注入 Depends,对象不会自动创建
模块全局作用域 ❌ 不可以 不在请求上下文中,request 不存在
startup / shutdown 事件中 ❌ 不可以使用 request / Depends 应直接用 app.state 或显式传参

✅ 正确示例

python 复制代码
# 路由函数中
from fastapi import Request, Depends

@app.get("/info")
def get_info(request: Request, config: Config = Depends(get_config)):
    return {"url": config.LLM_MODEL_URL}

❌ 错误示例(类中使用 Depends)

python 复制代码
# 错误:FastAPI 不会自动创建此类,也不会注入 config
class MyService:
    def __init__(self, config: Config = Depends(get_config)):
        self.config = config

如需在类中使用配置,应该显式传入 config,例如:

python 复制代码
class MyService:
    def __init__(self, config: Config):
        self.config = config
相关推荐
屏什么录3 分钟前
电脑如何录屏幕视频和声音?从工具到代码,7 种方案帮你彻底搞定
前端·音视频开发
用户3600555790011 分钟前
Kestrel_VLLM_CUDA -09 · full-GPU decode:单 token 全设备
前端
kyriewen19 分钟前
我上手了 Vite+ 1.0:Node 不用自己装,lint 却翻车了
前端·javascript·程序员
松就是我9029821 分钟前
你的 PPT 不缺内容,缺一个讲它的人
前端
松就是我9029823 分钟前
别再熬夜做 PPT 了!输入一个主题,AI 帮你把整套幻灯片做好,还能随便改字
前端
吴凡wudianmei24 分钟前
每调一次模型都花钱?如何用工程手段把调用压到最少?
前端·后端·架构
李元_霸26 分钟前
基于 AI 的 Web 与 App 端到端测试实践
前端·人工智能
欣欣之王来了31 分钟前
Vue3项目脚手架:Vite vs Vue CLI怎么选?
前端·学习·架构·项目·vue3教程
用户27886072856743 分钟前
别把 tool.completed 当成业务成功:AI 工具权限审计的四层事件链
前端
陆柒1451 小时前
跟着 Webpack 配置学习前端工程化
前端