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 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
学Linux的语莫9 天前
python基础语法
开发语言·python
前端fighter9 天前
为什么需要dependencies 与 devDependencies
前端·javascript·面试
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python
veminhe9 天前
HTML5 浏览器支持
前端·html·html5