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 |

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

相关推荐
MSTcheng.20 分钟前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
OpenTiny社区22 分钟前
我用Vue 100%复制DeepSeek开源的网页App,代码更少,功能还更多!
前端·vue.js·github
MyBili31 分钟前
Chrome开发者工具入门:从看懂页面到高效调试
前端·chrome·谷歌浏览器·开发工具·chrome devtools·网页调式·网络请求分析
云起SAAS41 分钟前
手机靓号选号商城H5源码 完整前后台可直接运行
前端·javascript·后端
code2cat1 小时前
JavaScript编程篇之异步请求:切换到待办,为什么又显示了全部任务
前端·javascript
the局外人1 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__1 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python
Moment1 小时前
RSI 是怎样让 AI 改进自己的 ❓❓❓
前端·后端·面试
1-1=01 小时前
Vue 条件渲染和列表渲染
前端·javascript·vue.js
前端双越老师2 小时前
程序员 1v1 访谈系列第十六期:裸辞后失业半年了
前端·ai编程·全栈