补充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
相关推荐
闲云一鹤25 分钟前
nginx 快速入门教程 - 写给前端的你
前端·nginx·前端工程化
QCY1 小时前
「完全理解」1 分钟实现自己的 Coding Agent
前端·agent·claude
曲幽1 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
一拳不是超人1 小时前
Electron主窗口弹框被WebContentView遮挡?独立WebContentView弹框方案详解!
前端·javascript·electron
anyup1 小时前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
雮尘2 小时前
如何在非 Claude IDE (TARE、 Cursor、Antigravity 等)下使用 Agent Skills
前端·agent·ai编程
icebreaker2 小时前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 小时前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
wuhen_n2 小时前
代码生成:从AST到render函数
前端·javascript·vue.js
喝咖啡的女孩2 小时前
浏览器前端指南
前端