跳到内容

中间件

您可以在 FastAPI 应用程序中添加中间件。

“中间件”是一个函数,它在任何特定路径操作处理之前都会与每个请求一起工作。以及在返回每个响应之前。

  • 它接收来自您的应用程序的每个请求
  • 然后它可以对该请求执行某些操作或运行任何必要的代码。
  • 然后,它将请求传递给应用程序(通过某些路径操作)的其余部分进行处理。
  • 然后,它接收由应用程序(通过某些路径操作)生成的响应
  • 它可以对该响应执行某些操作或运行任何必要的代码。
  • 然后,它返回响应

“技术细节”

如果您使用 yield 具有依赖项,则退出代码将在中间件之后运行。

如果存在任何后台任务(将在后面介绍),它们将在所有中间件之后运行。

创建中间件

要创建中间件,您需要在函数顶部使用装饰器 @app.middleware("http")

中间件函数接收

  • request
  • 一个函数 call_next,它将接收 request 作为参数。
    • 此函数将 request 传递给相应的路径操作
    • 然后,它返回由相应的路径操作生成的 response
  • 然后,您可以在返回它之前进一步修改 response
import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

提示

请记住,可以添加自定义专有标头 使用 'X-' 前缀

但是,如果您有希望浏览器中的客户端能够看到的自定义标头,则需要将它们添加到 CORS 配置中 (CORS(跨源资源共享)),使用参数 expose_headers,如 Starlette 的 CORS 文档 中所述。

“技术细节”

您也可以使用 from starlette.requests import Request

FastAPI 为您(开发人员)提供了便利。但它直接来自 Starlette。

response 之前和之后

您可以添加要在 request 上运行的代码,在任何路径操作接收它之前。

以及在生成 response 之后,在返回它之前。

例如,您可以添加一个自定义标头 X-Process-Time,它包含处理请求并生成响应所花费的秒数

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

提示

这里我们使用 time.perf_counter() 而不是 time.time(),因为它在这些用例中可能更精确。🤓

其他中间件

您可以在 高级用户指南:高级中间件 中详细了解其他中间件。

您将在下一节中阅读有关如何在中间件中处理CORS 的内容。