补充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
相关推荐
沙蒿同学4 小时前
不引 Ghostscript:我用纯 Go 给 PDF 做了一场「压缩手术」
前端·后端·github
变与不变8065 小时前
jQuery细节以及使用应用场景
前端·javascript·jquery
SailingCoder7 小时前
【封闭结束1】端到端交付:Agent 一次请求如何走完全链路
前端·安全·ai·面试·agent·harness
小林ixn8 小时前
FastAPI + LangChain 实战:从 0 到 1 打造高性能 AI 后端服务
人工智能·langchain·fastapi
风骏时光牛马9 小时前
AI多模块协同自动化工作流
前端
zhangminghuan9 小时前
前端面试应对技巧
前端·面试·职场和发展
计算机魔术师9 小时前
潜伏14年的PHP致命洞,AI跑两天就交卷了
前端
IT_陈寒9 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
Python自动化直播11 小时前
智能脚本批量管理拆开看:导入、导出、重写、试听
前端·python·ai·秒播