FastAPI 教程翻译 - 用户指南 27 - 中间件

FastAPI 教程翻译 - 用户指南 27 - 中间件

FastAPI Tutorial - User Guide - Middleware

You can add middleware to FastAPI applications.

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

A “middleware” is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it.

『中间件』是一项功能,可在任何特定的路径操作处理之前,与每个请求一起使用。并在返回之前进行每个响应

  • It takes each request that comes to your application.

    它需要应用程序中的每个请求

  • It can then do something to that request or run any needed code.

    它可以对该请求执行某些操作或运行任何需要的代码。

  • Then it passes the request to be processed by the rest of the application (by some path operation).

    然后,它传递请求,由应用程序的其余部分(通过某些路径操作)处理。

  • It then takes the response generated by the application (by some path operation).

    它接受应用程序生成的响应(通过某些路径操作)。

  • It can do something to that response or run any needed code.

    它可以做些响应或运行任何需要的代码。

  • Then it returns the response.

    然后返回响应

Technical Details

技术细节

If you have dependencies with yield, the exit code will run after the middleware.

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

If there were any background tasks (documented later), they will run after all the middleware.

如果有任何后台任务(稍后记录),它们将在所有中间件之后运行。

Create a middleware

创建一个中间件

To create a middleware you use the decorator @app.middleware("http") on top of a function.

要创建中间件,请在函数顶部使用修饰符 @app.middleware("http")

The middleware function receives:

中间件功能接收:

  • The request.

    一个 request

  • A function call_next that will receive the request as a parameter.

    一个函数 call_next,它将接收 request 的参数。

    • This function will pass the request to the corresponding path operation.

      此功能会将 request 传递给相应的路径操作

    • Then it returns the response generated by the corresponding path operation.

      然后,它返回由相应的路径操作生成的 response

  • You can then modify further the response before returning it.

    您可以在返回之前进一步修改 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.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

Tip

提示

Have in mind that custom proprietary headers can be added using the ‘X-’ prefix.

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

But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (CORS (Cross-Origin Resource Sharing)) using the parameter expose_headers documented in Starlette’s CORS docs.

但是,如果您希望使浏览器中的客户端看到自定义标头,则需要将其添加到CORS配置中(CORS(跨域资源共享)),使用 Starlette’s CORS 文档 中记录的参数 expose_headers

Technical Details

技术细节

You could also use from starlette.requests import Request.

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

FastAPI provides it as a convenience for you, the developer. But it comes directly from Starlette.

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

Before and after the response

response 之前和之后

You can add code to be run with the request, before any path operation receives it.

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

And also after the response is generated, before returning it.

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

For example, you could add a custom header X-Process-Time containing the time in seconds that it took to process the request and generate a 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.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

Other middlewares

其他中间件

You can later read more about other middlewares in the Advanced User Guide: Advanced Middleware.

稍后,您可以在 高级用户指南:高级中间件 中阅读有关其他中间件的更多信息。

You will read about how to handle CORS with a middleware in the next section.

您将在下一部分中了解如何使用中间件处理 CORS。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值