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

相关推荐
M--Y18 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静18 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL12318 小时前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_0919 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
九英里路19 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
databook1 天前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈1 天前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao1 天前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
用户019027581611 天前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
2601_967979121 天前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt