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

不要在非路由函数(如类的 __init__ 方法或普通模块函数)中直接使用 Depends()request
Dependsrequest: 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
相关推荐
KaMeidebaby5 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl6 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
sugar__salt6 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
独特的螺狮粉6 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
pusheng20256 小时前
IFSJ全英文专访:中国创新力量重塑先进气体感知技术,赋能全球关键基础设施安全
前端·网络·人工智能·物联网·安全
AI_零食7 小时前
番茄钟鸿蒙PC Electron框架完成:状态机、定时器管理与专注力工具设计
前端·javascript·华为·electron·开源·鸿蒙·鸿蒙系统