在FastAPI中,依赖注入是一种强大的功能,它允许你轻松地将依赖项注入到你的路由处理程序函数中,以处理不同的任务,例如数据库访问、认证和配置管理。
FastAPI支持依赖注入通过以下方式:
- 使用参数注解: 你可以在路由处理程序函数的参数上使用Python的类型注解,告诉FastAPI你需要什么依赖项。FastAPI将根据类型自动查找或创建这些依赖项。
- 依赖注入容器: 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