Python FastAPI系列:Depends函数与依赖注入(DI)
FastAPI 提供了一种简化版的依赖注入系统。它允许在FastAPI程序运行时将外部组件(依赖项,包括函数、类、对象)注入到程序内部的函数或类中,而不是在函数内部直接创建或管理它们。
区别于传统的依赖注入模式,FastAPI 的依赖注入采用的是函数式依赖注入,基于 Python 的类型提示和 Depends()。它没有传统的 IoC 容器,而是通过函数或类直接声明依赖,框架在运行时自动解析和注入。
1、注入的方式
FastAPI 允许在路由函数、路由组、以及应用全局注入依赖项。现在我们希望在每个路由中可以根据token获得当前用户信息:
dependence.py文件,用于获取当前用户信息
# 外部组件,用于获取当前用户信息
async def get_current_user(token:str=None):
if token: # 可以根据实际业务补充具体逻辑
return {
"username": "faker"}
# 外部组件,用于检查用户是否登录,如果没有登录直接返回HTTP 401
async def check_login(token: str = None):
if not token:
raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED, detail="未登录")
1)没有使用注入的情形
from fastapi import FastAPI
from dependence import *
app = FastAPI()
@app.get("/")
async def hello_world():
user = await get_current_user() # 需要手动调用依赖项
return {
"user": user, "message": "Hello World!"}
2)路由函数注入
from fastapi import FastAPI, Depends
from dependence import *
app = FastAPI()
@app.get("/")
async def hello_world(user=Depends(get_current_user)): # 路由函数注入点
return {
"user": user, "message": "Hello World!"}
运行代码后:
- 当访问 http://127.0.0.1:8000/?token=geekabc 时就会返回用户信息
2)路由路径注入
from fastapi import FastAPI, Depends
from dependence import *
app = FastAPI()
@app.get("/",dependencies=[Depends(check_login)]) # 路由路径注入点
async def hello_world(user=Depends(get_current_user)): # 路由函数注入点
return {
"user": user, "message": "Hello World!"}
运行代码后:
- 当访问 http://127.0.0.1:8000/?token=geekabc 时就会返回用户信息
3)路由组注入
如果我们希望整个/user路由段可以先检查用户登录状态,然后返回当前用户信息时,可以为路由组注入了check_login,为路由注入了get_current_user:
from fastapi import FastAPI, Depends, APIRouter
from dependence import *
app = FastAPI()
user_routers = APIRouter(prefix="/user", dependencies=[Depends(check_login)])# 路由组注入点
@user_routers.get("/")
async def user_home(user=Depends(get_current_user)
1734



被折叠的 条评论
为什么被折叠?



