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

相关推荐
AIFQuant几秒前
Python实时外汇行情接入实战:WebSocket与REST K线查询
开发语言·python·websocket
杰克尼5 分钟前
FastAPI
fastapi
babe小鑫24 分钟前
生物统计学专业校招:SAS、R、Python学习顺序实用指南
python·学习·r语言
vx_Biye_Design26 分钟前
springboot游泳馆系统93765-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·spring·课程设计
固定资产管理系统软件43 分钟前
该去哪里找专业靠谱的智慧智能设备固定资产管理系统?
人工智能·python
ctlover1 小时前
LangChain 概述
python·langchain
专业程序开发源1 小时前
springbootLivehouse票务系统-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·pygame
李高钢1 小时前
Python Django 框架入门:从零搭建你的第一个 Web 应用
前端·python·django
2601_966949651 小时前
从轮询到策略消费:量化系统如何高效处理五档盘口数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
萧鼎1 小时前
2026实战:用 accelerate 库加速 PyTorch 训练,核心语法与避坑指南
python·开源·教程·python库·accelerate