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

相关推荐
淘气的小猴子1 分钟前
Python 魔术方法入门
python
我要见SA姐110 分钟前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
ide·vscode·python·自动化·编辑器
沉下心来学鲁班1 小时前
初识DeepAgents搭建第一个智能体
人工智能·python·langchain
ctlover1 小时前
数据结构:树
数据结构·python
触底反弹2 小时前
🐍 Python 语法全景图:一个 print() 引发的深度探索
python
元Y亨H2 小时前
告别依赖地狱与打包崩溃:Python 项目环境治理与 PyInstaller 避坑实践
python
aramae3 小时前
Python 使用库:标准库与第三方库实战
服务器·开发语言·windows·python
IamZJT_3 小时前
Agent 系统工程 01|模型之外,Harness 到底该负责什么?
人工智能·python·程序员
沧海一笑-dj3 小时前
【Python】Python学习笔记-Python 核心基础
人工智能·python·ai·解释型语言
用户76855341255383 小时前
Python 并发怎么选?一篇讲清 threading、multiprocessing、asyncio 的边界
python