中间件

FastAPI中我们可以使用@app.middleware('http')装饰器来创建中间件,下面是一个例子。

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware('http')
async def calc_time(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.get('/foo')
async def foo():
    return {'message': 'ok'}

代码中我们创建了一个calc_time()函数作为中间件,它的作用是计算请求处理时间并添加一个响应头。我们可以看到中间件接收两个参数,request是请求对象,我们可以从其中读取请求URL、请求头、请求参数等信息;call_next是一个函数,它代表着对于具体的路由处理函数的调用,它的返回值是Response对象。通过这些参数,我们可以实现对于请求和处理的拦截。

作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。