FastAPI - 依赖注入3

在FastAPI中,依赖注入是一种强大的功能,它允许你轻松地将依赖项注入到你的路由处理程序函数中,以处理不同的任务,例如数据库访问、认证和配置管理。

FastAPI支持依赖注入通过以下方式:

  1. 使用参数注解: 你可以在路由处理程序函数的参数上使用Python的类型注解,告诉FastAPI你需要什么依赖项。FastAPI将根据类型自动查找或创建这些依赖项。
  2. 依赖注入容器: FastAPI内部使用一个依赖注入容器来管理依赖项。这个容器会在运行时解析参数注解,自动处理依赖项的创建和生命周期管理。

https://zhuanlan.zhihu.com/p/658917476

https://fastapi.tiangolo.com/zh/tutorial/dependencies

型应用程序依赖项管理

具体的依赖项为可调用类型(callable),如函数(function),类(class)

在项目根目录下创建dependencies.py文件用于管理依赖项

# -*- coding:utf-8 –*-
from typing import Annotated

from fastapi import Header, HTTPException


async def get_query_token(token: str = ""):
    if token != "vvv":
        raise HTTPException(status_code=400, detail="No vvv token provided")

修改routers/member.py文件

# -*- coding:utf-8 –*-
from fastapi import Depends,APIRouter

from dependencies import get_query_token

router = APIRouter(prefix="/member",tags=["会员模块"],dependencies=[Depends(get_query_token)],)


@router.get("/list",description="会员列表")
async def list():
    return {"message":"成功获取会员列表"}


@router.post("/login",description="会员登录")
async def login():
    return {"message": "member login"}

上面的依赖项要求我们请求时必须带上参数token,并且其值为vvv

浏览器打开http://127.0.0.1:8000/member/list?token=vvv

当然也可以在main.py里面执行依赖项

先在dependencies.py里面增加另外一个依赖项

async def another_depend(token2: str = ""):
    if token2 != "vvv2":
        raise HTTPException(status_code=400, detail="No vvv2 token provided")

修改main.py文件

# -*- coding:utf-8 –*-
from fastapi import Depends,FastAPI

from dependencies import another_depend
from routers import member

app = FastAPI(
    title="文档标题",
    description="关于API文档的补充说明",
    version="1.0.0",
    docs_url="/docs",
    dependencies=[Depends(another_depend)],
)


app.include_router(member.router)

浏览器打开http://127.0.0.1:8000/member/list?token=vvv&token2=vvv2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值