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

相关推荐
geovindu1 分钟前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
tryCbest33 分钟前
Python 文件操作
服务器·python
涛声依旧-底层原理研究所1 小时前
Agent 长任务可靠性设计:实现暂停、恢复、续跑与崩溃重启的完整方案
人工智能·python·系统架构
AC赳赳老秦1 小时前
防火墙规则批量配置实战:OpenClaw 自动生成模板、批量下发与合规性校验全解析
java·开发语言·人工智能·python·github·php·openclaw
小小编程路1 小时前
如何优化while循环的性能?
python
lzqrzpt2 小时前
LED驱动电源选型标准与工程应用技术要点解析
python·单片机·嵌入式硬件·物联网
Maiko Star3 小时前
Python核心语法——函数
开发语言·python
linzᅟᅠ3 小时前
README
人工智能·python
瓶中怪3 小时前
ROS2 机器人软件系统
linux·c++·python·ubuntu·vmware·ros2·机器人软件开发
满怀冰雪3 小时前
22_Runnable接口源码拆解_LCEL管道语法背后_invoke_stream_batch究竟做了什么
python·batch