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

相关推荐
qq_513728045 小时前
StaleElementReferenceException(陈旧元素引用异常)
python
千里码aicood5 小时前
基于Python的电商数据采集系统(大数据+爬虫)
开发语言·python
战略性的菠萝5 小时前
研究生基础-Python快速入门(终)——面向对象
python
陈皮波比茶5 小时前
Python项目实战-网络机器人(爬虫)
开发语言·网络·爬虫·python·机器人
winfredzhang6 小时前
从零构建家庭照片管理系统:Django 模块化单体实战,以及我踩到的 4 个真实坑
python·postgresql·django·sqlite·bootsrap
jyOverQ6 小时前
LangGraph 流式执行详解:stream、astream 与 stream_mode 怎么选?
python·langchain
闲猫6 小时前
LangGraph / Capabilities / Stores
python·agent·langgraph
pjj198546 小时前
机器学习-NumPy2
人工智能·python·机器学习
OPEN-F7 小时前
Python进阶教程:单元测试与代码质量
开发语言·python·单元测试
Logintern097 小时前
装饰器和洋葱模式的区分
开发语言·python·架构