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

相关推荐
0566461 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华2 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO2 小时前
GEO技术服务选型指南
大数据·人工智能·python
软萌萌的12 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Dxy12393102164 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
持敬chijing5 小时前
Python概述
开发语言·python
赤羽尾风6 小时前
NumPy快速入门
python·numpy
倒流时光三十年7 小时前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
久久学姐8 小时前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm