0%

FastAPI自学教程(57) - 高级依赖项配置

1. 可调用实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from fastapi import Depends, FastAPI

app = FastAPI()

class FixedContentQueryChecker:
def __init__(self, fixed_content: str):
self.fixed_content = fixed_content

def __call__(self, q: str = ""):
return self.fixed_content in q if q else False

checker = FixedContentQueryChecker("bar")

@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
return {"fixed_content_in_query": fixed_content_included}
  • 通过实现类的__call__方法创建可调用实例,使得类实例可作为依赖项注入路径操作函数
  • 请求处理流程:
    graph TD
      A[客户端请求] --> B[初始化FixedContentQueryChecker实例]
      B --> C[调用__call__方法校验参数]
      C --> D{校验结果}
      D -->|True| E[返回True]
      D -->|False| F[返回False]
      E & F --> G[响应结果]

2. 参数化实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ContentValidator:
def __init__(self, min_length: int):
self.min_length = min_length

def __call__(self, content: str):
return len(content) >= self.min_length

title_validator = ContentValidator(5)
desc_validator = ContentValidator(20)

@app.post("/articles/")
async create_article(
title_valid: bool = Depends(title_validator),
desc_valid: bool = Depends(desc_validator)
):
return {"title_valid": title_valid, "desc_valid": desc_valid}
  • 利用__init__方法实现依赖项参数化,同一验证类可生成不同校验规则的实例
  • 优势:
    • 避免为不同参数阈值编写多个相似验证函数
    • 支持动态配置校验规则(如从配置文件读取参数)
    • 通过实例化参数实现业务规则复用

3. 全局依赖项配置

1
2
3
4
5
6
7
8
9
async def security_check(api_key: str = Header(...)):
if api_key != "SECRET_123":
raise HTTPException(403)

app = FastAPI(dependencies=[Depends(security_check)])

@app.get("/private-data")
async def sensitive_data():
return {"data": "confidential"}
  • 在应用初始化时通过dependencies参数声明全局依赖项,自动应用于所有路径操作
  • 典型应用场景:
    • 全站身份验证
    • 请求日志记录
    • 流量控制
    • 请求头统一校验

测试命令示例:

1
curl -X GET "http://localhost:8000/query-checker/?q=bar"