Python web框架fastapi中间件的使用

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,基于标准 Python 类型提示。中间件在 FastAPI 中是一个强大的工具,允许你在请求到达路由处理函数之前或响应返回给客户端之后执行一些代码。

下面是一个使用 FastAPI 中间件的简单示例,这个中间件会记录每个请求的详细信息,包括请求的 IP 地址、请求路径、请求方法以及响应时间。

首先,确保你已经安装了 FastAPI:

复制代码
bash复制代码

|---|-----------------------|
| | pip install fastapi |

然后,你可以创建一个中间件并在 FastAPI 应用中使用它:

复制代码

python复制代码

|---|-------------------------------------------------------------------------------------------|
| | from fastapi import FastAPI, Request, Response |
| | from fastapi.middleware.base import BaseHTTPMiddleware |
| | from datetime import datetime |
| | import time |
| | |
| | app = FastAPI() |
| | |
| | class RequestLogger(BaseHTTPMiddleware): |
| | async def __call__(self, request: Request, call_next): |
| | start_time = time.time() |
| | response = await call_next(request) |
| | process_time = (time.time() - start_time) * 1000 |
| | print(f"Request from {request.client.host} at {datetime.now()}") |
| | print(f" Method: {request.method}, Path: {request.url.path}") |
| | print(f" Response Status: {response.status_code}, Process Time: {process_time:.2f}ms") |
| | return response |
| | |
| | app.add_middleware(RequestLogger) |
| | |
| | @app.get("/") |
| | async def read_root(): |
| | return {"Hello": "World"} |
| | |
| | @app.get("/items/{item_id}") |
| | async def read_item(item_id: int, q: str = None): |
| | return {"item_id": item_id, "q": q} |

在这个示例中,我们定义了一个名为 RequestLogger 的中间件类,它继承自 BaseHTTPMiddleware。这个中间件在请求处理前后记录了一些信息,包括请求的 IP 地址、请求方法、请求路径、响应状态码以及处理时间。然后,我们使用 app.add_middleware(RequestLogger) 将这个中间件添加到 FastAPI 应用中。

当你运行这个应用并发送请求时,你会在控制台看到类似以下的输出:

复制代码

bash复制代码

|---|---------------------------------------------------------|
| | Request from 127.0.0.1 at 2023-10-23 15:00:00.000000 |
| | Method: GET, Path: / |
| | Response Status: 200, Process Time: 123.45ms |

这个输出可以帮助你了解应用的运行情况,包括每个请求的处理时间和响应状态码等信息。

相关推荐
kyriewen118 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
极梦网络无忧9 小时前
OpenClaw 基础使用说明(中文版)
python
codeJinger9 小时前
【Python】操作Excel文件
python·excel
XLYcmy10 小时前
一个针对医疗RAG系统的数据窃取攻击工具
python·网络安全·ai·llm·agent·rag·ai安全
Islucas10 小时前
Claude code入门保姆级教程
python·bash·claude
skywalk816310 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
萝卜白菜。10 小时前
TongWeb7.0相同的类指明加载顺序
开发语言·python·pycharm
赵钰老师10 小时前
【ADCIRC】基于“python+”潮汐、风驱动循环、风暴潮等海洋水动力模拟实践技术应用
python·信息可视化·数据分析
爬山算法10 小时前
MongoDB(80)如何在MongoDB中使用多文档事务?
数据库·python·mongodb