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

相关推荐
相思半3 分钟前
机器学习模型实战全解析
大数据·人工智能·笔记·python·机器学习·数据挖掘·transformer
xingzhemengyou110 分钟前
python datetime模块使用
前端·python
2401_8414956424 分钟前
【LeetCode刷题】跳跃游戏
数据结构·python·算法·leetcode·游戏·贪心算法·数组
BoBoZz1941 分钟前
MarchingCases marchingcubes算法15种情况的展示
python·vtk·图形渲染·图形处理
彼岸花开了吗1 小时前
构建AI智能体:五十二、反应式智能体:基于“感知-行动”,AI世界的条件反射
人工智能·python·agent
weixin_429690721 小时前
# 数字人系统开发:如何选择可靠的开源方案在人工智能和虚
人工智能·python·开源
艾上编程1 小时前
《Python实战小课:数据分析场景——解锁数据洞察之力》导读
python·数据挖掘·数据分析
Lyinj1 小时前
从一个编辑校验问题谈接口设计的边界
java·spring boot·python·学习
纪伊路上盛名在1 小时前
文献阅读自动化1-批量检索、更新文献
python·自动化·文献阅读·科研日常·流程化
梦白.1 小时前
Python字符串类型
linux·python