我正在关注 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 之前定义中间件
最佳答案
documentation about middleware提到如果
(...) you want a client in a browser to be able to see [the custom headers], you need to add them to your CORS configurations, using the parameter
expose_headers
documented in Starlette's CORS docs.
关于python-3.x - 如何在 FastAPI 中使用带路由的中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308827/