0

我在这里关注 FastAPI 文档并尝试使用中间件实现路由。我的主要内容包括:

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 之前定义中间件

4

1 回答 1

1

关于中间件的文档提到如果

(...) 您希望浏览器中的客户端能够看到 [自定义标头],您需要使用Starlette 的 CORS 文档中记录的参数将它们添加到您的CORS 配置中。expose_headers

于 2020-01-03T02:42:03.507 回答