python-3.x - 如何在 FastAPI 中使用带路由的中间件

标签 python-3.x fastapi

我正在关注 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/

相关文章:

python - python 3.5 的 Pygame 安装

python - 数据框列之间所有可能组合的计数

python - 使 FastAPI WebSockets 的 CPU 密集型任务异步

python - 在 FastAPI 中覆盖 jsonable_encoder 的默认编码器

python - 如何设置 Pydantic 字段上的所有枚举值?

python - 使用 multiprocessing.manager 的问题

python - 在 tqdm 中的 for 循环后更改描述

python - StringProperty 的 TextInput 的 kivy 引用文本

python - Fastapi python 代码执行速度受 uvicorn 与 gunicorn 部署的影响

python - FastAPI - 未填充 ENUM 类型模型