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

相关推荐
金融大 k4 分钟前
Python 全球指数监控面板:TickDB + REST + WebSocket 完整方案
python·websocket
啊哈哈121387 分钟前
系统设计复盘:为什么 Agent 的 ReAct 循环必须内嵌确定性保护层——以 FitMind 健康助手的路由与步骤控制为例
人工智能·python·react
一颗牙牙1 小时前
安装mmcv
开发语言·python·深度学习
大数据魔法师1 小时前
Streamlit(二)- Streamlit 架构与运行机制
python·web
m0_470857642 小时前
PHP怎么实现工厂模式_Factory模式编写指南【指南】
jvm·数据库·python
大数据魔法师2 小时前
Streamlit(三)- Streamlit 多页面应用开发
python·web
我的xiaodoujiao2 小时前
API 接口自动化测试详细图文教程学习系列20--结合Pytest框架使用
python·学习·测试工具·pytest
python在学ing2 小时前
前端-CSS学习笔记
前端·css·python·学习
IT策士3 小时前
Django 从 0 到 1 打造完整电商平台:为什么用 Django 做电商?
后端·python·django
zkkkkkkkkkkkkk3 小时前
Linux进行管理工具Supervisor配置与使用
linux·python·supervisor