Python框架篇:FastApi-中间件使用
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start = time.time()
response = await call_next(request)
process_time = time.time() - start
response.headers["X-Process-Time"] = str(process_time)
return response
@app.middleware("http")
async def custom_middleware_second(request: Request, call_next):
# 可以在调用下一个中间件之前进行一些操作
response = await call_next(request)
# 也可以在之后进行一些操作
return response
@app.get("/")
async def main():
return JSONResponse({"message": "Hello World"})
这个示例代码定义了两个简单的HTTP中间件,并展示了如何在FastAPI应用中使用它们。每个中间件都有不同的功能,第一个中间件计算请求的处理时间并将其添加到响应头中,第二个中间件可以用作其他可能的前处理或后处理操作。最后,我们定义了一个简单的路由以供测试。
评论已关闭