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

相关推荐
郝学胜-神的一滴4 分钟前
深度拆解Python迭代协议:从底层原理到核心实践,解锁异步编程的基石
java·网络·python
2401_8331977311 分钟前
更优雅的测试:Pytest框架入门
jvm·数据库·python
weixin_3077791323 分钟前
2025年中国研究生数学建模竞赛A题:通用神经网络处理器下的核内调度问题——解决方案与实现
开发语言·人工智能·python·数学建模·性能优化
2501_9249526925 分钟前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
2401_8914821728 分钟前
Python多线程与多进程:如何选择?(GIL全局解释器锁详解)
jvm·数据库·python
2401_8512729928 分钟前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python
小陈的进阶之路33 分钟前
requests接口自动化测试
python
Yuer202534 分钟前
EDCA OS体系下的:QAS v0.1 实验框架(Python 版)
python·ai量化·edca os
一招定胜负39 分钟前
【实战】Python + 讯飞语音识别 + 通义千问:课堂视频自动转结构化教学数据
python·音视频·语音识别