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

相关推荐
yaoxin52112329 分钟前
497. Java 反射 - 使用反射读取注解
java·开发语言·python
2019一路前行41 分钟前
Python 函数式编程
开发语言·python
专注仿真1 小时前
问答大模型技术方案算法实现-RAPTOR树构建算法与BEG集成使用
python·算法
从小就看凹凸曼^o^3 小时前
Python基础5 - 字典与集合:(1)字典
开发语言·python
小赵AI手记3 小时前
技术拆解(十七)具身智能:机器人动作生成为何走向Diffusion Policy?
人工智能·笔记·python·机器人
本地化文档3 小时前
poethepoet-docs-l10n
python·github·gitcode·sphinx
baopixiaoz3 小时前
AI量化策略师|Web3 量化交易研究员
大数据·人工智能·python·区块链
Uncommon.4 小时前
使用Pytorch自动计算梯度
人工智能·pytorch·python
阿标的博客4 小时前
Python实训案例(二):输出植物证书
python
流浪0014 小时前
Python基础语法(三):函数
开发语言·python