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

相关推荐
bosins1 天前
基于Python实现PDF文件个人隐私信息检查
开发语言·python·pdf
bosins1 天前
基于Python开发PDF文件元数据查看器
开发语言·python·pdf
小北方城市网1 天前
第 10 课:Python 全体系实战整合与职业进阶指南(完结篇)
大数据·开发语言·数据库·python
WXG10111 天前
【Flask-10】modbus tcp通信
python·tcp/ip·flask
540_5401 天前
ADVANCE Day31
人工智能·python·机器学习
The star"'1 天前
Python
开发语言·python·pygame
luoluoal1 天前
基于python的文件销毁工具(源码+文档)
python·mysql·django·毕业设计·源码
量化风云1 天前
2026量化新基建(二) - sqlite 与 sqlite-utils
数据库·python·sqlite·量化交易·量化交易课程
yuhaiqun19891 天前
发现前端性能瓶颈的巧妙方法:建立“现象归因→分析定位→优化验证”的闭环思维
前端·经验分享·笔记·python·学习·课程设计·学习方法
Python大数据分析@1 天前
使用Dify搭建工作流,实现自动化商品采集分析
运维·python·自动化·网络爬虫