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

相关推荐
Wx-bishekaifayuan27 分钟前
django个性化旅游路线推荐平台49005-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
小白快快跑哦1 小时前
python-字符串全解(六):正则表达式-量词
python·正则表达式·字符串
禹凕2 小时前
机器学习之Selenium(Machina Learning about Selenium)
爬虫·python·selenium·测试工具·机器学习
ebiobiz4 小时前
基于 GD32 Embedded Builder (GEB) 与 Nimmake 的 MCU 工程搭建指南
c++·python·单片机·嵌入式硬件·mcu
老歌老听老掉牙4 小时前
穿越时空的物流密码:VRP与VRPTW的深度剖析及实战求解
python·物流·vrp
FYKJ_20104 小时前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
ShyanZh5 小时前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
小静AI工程实验室5 小时前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法
xzal125 小时前
GESP Python笔记
笔记·python·算法
半日闲dusknook5 小时前
我给 AI 写了个「音频编译器」:把「听起来还行」变成 PASS/FAIL
python