如何在FastAPI中通过路由使用中间件

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

我正在遵循FastAPI文档here,并尝试使用中间件来实现路由。我的主要内容包括:

app = FastAPI()


app.include_router(
    SomeService.router,
    prefix="/services",
    tags=["services"]
)


@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

发送请求时,它会正确执行并返回正确的值,但不包含通过中间件附加的值。

我已经尝试在服务路径中定义中间件并在app.include_router之前定义中间件

python-3.x fastapi
1个回答
0
投票

您的示例似乎完全按预期运行,如何检查响应头?

$ curl http://localhost:8000 -D-
HTTP/1.1 404 Not Found
date: Wed, 18 Dec 2019 22:02:15 GMT
server: uvicorn
content-length: 22
content-type: application/json
x-process-time: 0.0009450912475585938
© www.soinside.com 2019 - 2024. All rights reserved.