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

相关推荐
Ticnix10 分钟前
RAG 的坑不在检索,在"对齐":pgvector 实战手记
python·agent·全栈
kyrie_sakura10 分钟前
python学习笔记14 -- FastAPI
笔记·python·学习·fastapi
春涧草茶43 分钟前
慢就是快12-2三种访问权限|getter与setter|魔法方法
开发语言·python
夜雪一千1 小时前
如何使用Python做舆情分析
人工智能·python·数据分析
Ticnix2 小时前
MCP 工具拿不到 user_id?用 contextvars 做请求级用户隔离
python·agent·mcp
gb42152872 小时前
WPS 里的 Word快速合成照片
python
爱和冰阔落2 小时前
【Linux】条件变量为什么必须配合互斥锁:从 pthread_cond_wait 到阻塞队列
linux·运维·c++·缓存·中间件·安卓
databook2 小时前
Python 常用统计图表实战指南
python·数据分析·数据可视化
wang_yb2 小时前
Python 常用统计图表实战指南
python·数据分析·databook