如何正确注释 FastAPI 中间件的 `call_next` 参数?

问题描述 投票:0回答:1

我正在尝试改编 FastAPI docs 中的示例来创建中间件:

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    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

不过这里的

call_next
参数没有注释。当我仅使用
typing.Callable
时,我会从
mypy
:

收到错误
error: Missing type parameters for generic type "Callable"  [type-arg]

参数的具体标注方式是怎样的?

python fastapi python-typing mypy
1个回答
0
投票

call_next
是一个异步函数,它接受
Request
并返回
Response
,因此类型为
Callable[[Request], Awaitable[Response]]
:

from typing import Awaitable, Callable

from fastapi import FastAPI, Request, Response

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
):
    ...
© www.soinside.com 2019 - 2024. All rights reserved.