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 分钟前
Tushare接口文档:指数成分和权重(index_weight)
大数据·数据库·python·金融·量化投资
小大宇9 分钟前
python pandas dataFrame sqlAlchemy案例
python·pandas
淼澄研学11 分钟前
Python进阶实战:深入解析推导式与生成器等5大核心特性
开发语言·python
xlrqx1 小时前
商丘家电清洗培训零基础学习需掌握哪些要点零基础到底能不能学
python·学习
卷无止境1 小时前
Python虚拟环境江湖:从venv到uv,如何避开依赖冲突的坑
后端·python
玉鸯1 小时前
Agent Harness 工程核心架构拆解与 300 行代码实现
python·agent
米码收割机1 小时前
【Python】Django 电子设备商城系统(源码+说明文档)[独一无二]
开发语言·python·django
互联网中的一颗神经元1 小时前
小白python入门 - 38. 动态内容:接口优先与自动化扫盲
开发语言·python·自动化
卷无止境1 小时前
模块与包:Python 代码组织的两层逻辑
后端·python
夏日清风有你2 小时前
OpenDataLab 数据集下载
python