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 |

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

相关推荐
寒草9 分钟前
「寒草呈献」工作六年,是否仍有创造未来的勇气 ✨
前端·后端
HackTwoHub10 分钟前
解锁 AI 红队全新玩法!Claude-Red 攻防 Skill 库,内置 SQLi、XXE、文件上传等 Web 专项 Skill,一键导入快速落地渗透实战
前端·人工智能·web安全·网络安全·自动化·系统安全
石小石Orz11 分钟前
如何设计一个优秀的 Skills
前端·人工智能
浊酒南街19 分钟前
subprocess.run函数介绍
python
星空23 分钟前
【无标题】
python
程序员爱钓鱼1 小时前
Rust 切片 Slice 详解:安全访问连续数据
前端·后端·rust
alexander0683 小时前
CSS 类选择器组合
前端·css
寅时码8 小时前
React 之死·终章:一个 useRef,把闭包陷阱、依赖数组、漫天 rerender 全送走
前端·react.js·ai编程
不好听6138 小时前
HTML 事件监听机制:从 DOM Level 0 到 React 合成事件
前端·react.js·html
wordbaby9 小时前
为什么刷新页面就 404?聊聊 SPA 路由与 Nginx 的那点事
前端