我在这里关注 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 之前定义中间件