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

相关推荐
the局外人8 分钟前
学习 FastAPI 的 Day 2:用异步 ORM 完成增删改查
后端·python·fastapi
智搜广告11 分钟前
GEO优化公司怎么选?智搜广告从三个维度帮你判断
大数据·人工智能·python·elasticsearch·microsoft·geo
「、皓子~14 分钟前
海狸IM 2.1 私有化部署从零到一:中间件、微服务与 Nginx 全流程
nginx·flutter·微服务·中间件·开源软件·im·海狸im
wanglei20070821 分钟前
软件架构设计中,各个组件之间的通信方式有哪些?
python
会飞的拖把27 分钟前
Python 面向对象编程详解:从类与对象到动态属性方法
开发语言·python
微小冷33 分钟前
Python CasADi初步教程
python·控制·模型预测·casadi·符号表达式·sx
cpolar技术支持1 小时前
requirements.txt 能安装不等于安全:用 pip-audit 检查 Python 依赖,cpolar 临时分享脱敏报告
python·cpolar·requirements·依赖安全·pip-audit
测试19981 小时前
Jmeter接口自动化生成测试报告html格式详解
自动化测试·python·测试工具·jmeter·职场和发展·测试用例·接口测试
pjj198541 小时前
Hadoop-python中使用大数据
大数据·hadoop·python
小刘在重生~1 小时前
Django|Excel 批量上传、Form/ModelForm 文件上传、Media 媒体文件配置
python·django·excel