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

相关推荐
都叫我大帅哥1 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`3 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
路人蛃8 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
qiqiqi(^_×)8 小时前
卡在“pycharm正在创建帮助程序目录”
ide·python·pycharm
Ching·9 小时前
esp32使用ESP-IDF在Linux下的升级步骤,和遇到的坑Traceback (most recent call last):,及解决
linux·python·esp32·esp_idf升级
吗喽15434518810 小时前
用python实现自动化布尔盲注
数据库·python·自动化
hbrown10 小时前
Flask+LayUI开发手记(十一):选项集合的数据库扩展类
前端·数据库·python·layui
猫头虎10 小时前
什么是 npm、Yarn、pnpm? 有什么区别? 分别适应什么场景?
前端·python·scrapy·arcgis·npm·beautifulsoup·pip