You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为FastAPI中间件的`call_next`参数正确添加类型注解?

FastAPI中间件call_next参数的标准类型注解方式

call_next是一个接收Request对象、返回可等待(异步)Response对象的调用对象,正确的类型注解需要结合Callable与Awaitable来定义,具体步骤如下:

  1. 导入所需的类型依赖:
from fastapi import Request, Response
from typing import Callable, Awaitable
  1. 为call_next添加完整的类型注解:
@app.middleware("http")
async def add_process_time_header(request: Request, call_next: Callable[[Request], Awaitable[Response]]):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

注解说明

Callable[[Request], Awaitable[Response]]明确了:

  • 该调用对象接受单个Request类型参数
  • 返回值是一个可被await的Response对象

这样的注解完全匹配call_next的实际行为,能解决mypy抛出的"Missing type parameters for generic type 'Callable'"错误。

内容的提问来源于stack exchange,提问作者planetp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:27:01