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

相关推荐
轻竹办公PPT几秒前
AI 生成 2026 年工作计划 PPT,逻辑清晰度对比测试
人工智能·python·powerpoint
Direction_Wind5 分钟前
抖音视频下载,直播间监控,直播间发言采集,最新加密算法
python·node.js
旦莫12 分钟前
使用OCR加持的APP自动化测试
python·测试开发·自动化·ocr·pytest·ai测试
天若有情67314 分钟前
用 Python 爬取电商商品数据:从入门到反爬破解
开发语言·python
七夜zippoe17 分钟前
RabbitMQ与Celery深度集成:构建高性能Python异步任务系统
分布式·python·rabbitmq·celery·amqp
Hello阿尔法18 分钟前
SCons 一款基于 Python 的自动化构建工具
python·跨平台·构建工具·scons
Pyeako23 分钟前
Opencv计算机视觉--图像边缘检测
人工智能·python·opencv·计算机视觉·sobel·canny·图像边缘检测
深蓝电商API28 分钟前
Scrapy爬取Ajax动态加载页面三种实用方法
爬虫·python·scrapy·ajax
姓刘的哦30 分钟前
推理PyTorch模型的方法
人工智能·pytorch·python