fastapi自定义中间件

fastapi自定义中间件

1、自定义中间件类

python 复制代码
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware

class MyMiddleware(BaseHTTPMiddleware):
    def __init__(self, app,*args, **kwargs):
        super().__init__(app,*args, **kwargs)

    async def dispatch(self, request: Request, call_next):
        print("MyMiddleware =============================== ")
        # 接收来自客户端的Request请求;
        headers = dict(request.scope['headers'])
        # 将Request请求传回原路由
        response = await call_next(request)
        return response

2、使用自定义中间件

python 复制代码
app.add_middleware(MyMiddleware)

3、中间件执行顺序,从下往上执行

python 复制代码
app.add_middleware(xx1)
app.add_middleware(xx2)

会先执行xx2再执行xx1

相关推荐
corpse20101 分钟前
trae下载依赖包特别慢!!!
开发语言·python
诸神缄默不语3 分钟前
Windows系统无法直接用uv安装pyqt5,但可以用uv pip安装
python
中年程序员一枚11 分钟前
同时装有Python3.12和Python3.14,历史原因Python3.12出现问题,需要删除,但是删除不干净
python
爱笑的眼睛1130 分钟前
超越翻转与裁剪:面向生产级AI的数据增强深度实践与多模态演进
java·人工智能·python·ai
一位代码38 分钟前
python3 | XPath 安装及导入方法
python
张彦峰ZYF42 分钟前
Python 模式匹配与高效正则表达式:从语言特性到工程级简单实践
python·正则表达式
zhishidi1 小时前
Spring @Scheduled注解调度机制详解
java·python·spring
qq_356196951 小时前
Day 43图像数据与显存机制@浙大疏锦行
python
yaoh.wang1 小时前
力扣(LeetCode) 94: 二叉树的中序遍历 - 解法思路
python·算法·leetcode·面试·职场和发展·二叉树·跳槽
摸鱼仙人~1 小时前
Flask-SocketIO 连接超时问题排查与解决(WSL / 虚拟机场景)
后端·python·flask