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

相关推荐
失散1319 分钟前
Python——1 概述
开发语言·python
萧鼎21 分钟前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
qq_2515335922 分钟前
使用 Python 提取 MAC 地址
网络·python·macos
Data_agent2 小时前
学术爬虫实战:构建知网论文关键词共现网络的技术指南
python·算法
_一路向北_4 小时前
爬虫框架:Feapder使用心得
爬虫·python
皇族崛起4 小时前
【3D标注】- Unreal Engine 5.7 与 Python 交互基础
python·3d·ue5
你想知道什么?5 小时前
Python基础篇(上) 学习笔记
笔记·python·学习
Swizard5 小时前
速度与激情:Android Python + CameraX 零拷贝实时推理指南
android·python·ai·移动开发
一直跑6 小时前
Liunx服务器centos7离线升级内核(Liunx服务器centos7.9离线/升级系统内核)
python
leocoder6 小时前
大模型基础概念入门 + 代码实战(实现一个多轮会话机器人)
前端·人工智能·python