第 9 章: 依赖项
本章概述
学习FastAPI的依赖项系统,实现代码复用和逻辑分离。
9.1 路径依赖(API方法装饰器)
使用Depends声明依赖:
from fastapi import Depends
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/")
def read_users(db: Session = Depends(get_db)):
return db.query(User).all()9.2 将依赖定义为变量
from fastapi import Depends
async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
return commons9.3 多层依赖
依赖可以依赖其他依赖:
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_current_user(db: Session = Depends(get_db)):
# 获取当前用户逻辑
user = get_user_from_token()
return user
@app.get("/me")
def read_me(current_user: User = Depends(get_current_user)):
return current_user9.4 依赖类的使用
from fastapi import Depends
class CommonQueryParams:
def __init__(self, q: str = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends(CommonQueryParams)):
return commons9.5yield vs return
使用yield可以在依赖中执行清理代码:
async def get_db():
db = SessionLocal()
try:
yield db # 提供数据库会话
finally:
db.close() # 请求处理后关闭会话小结
在本章中,我们学习了: - ✅ 使用Depends声明依赖 - ✅ 创建可重用的依赖函数 - ✅ 实现多层依赖注入 - ✅ 使用类作为依赖 - ✅ 使用yield实现清理逻辑
依赖项是FastAPI的强大功能,可以实现认证、数据库会话管理等。
第 10 章: 中间件介绍
本章概述
学习如何使用中间件拦截请求并在请求前或响应后执行操作。
10.1 创建中间件
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
import time
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response10.2 中间件的应用场景
- 记录请求日志
- 添加CORS头
- 身份验证
- 请求限流
- 错误处理
10.3 CORS中间件
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)小结
在本章中,我们学习了: - ✅ 创建中间件 - ✅ 在请求前和响应后执行代码 - ✅ 中间件的常见应用场景 - ✅ 配置CORS中间件
在下一章中,我们将学习用户认证!