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

相关推荐
qiqiqi(^_×)2 分钟前
pycharm Memory Settings无法保存
ide·python·pycharm
xzal123 分钟前
Python 中,and 和 or 运算符的运算规则
笔记·python
gf13211114 分钟前
【python_使用指定应用发送飞书卡片】
java·python·飞书
Dxy12393102165 分钟前
Python转Word为PDF:办公自动化的高效利器
python·pdf·word
Thomas.Sir8 分钟前
第十章:RAG知识库开发之【LangSmith 从入门到精通:构建生产级 LLM 应用的全链路可观测性平台】
人工智能·python·langsmith·langchian
初心未改HD8 分钟前
从Java转行大模型应用,Agent应用开发,Function Calling学习
人工智能·python
tigerlib9 分钟前
vscode python环境调试,不能调到环境内部,怎么解决
ide·vscode·python
今天又在摸鱼12 分钟前
py工程+爬虫
开发语言·python
李松桃14 分钟前
Python爬虫-第一课
开发语言·python
清水白石00815 分钟前
Python 项目 CI/CD 信心模型:证据驱动部署,从“勇敢上线”到“零风险发版”实战指南
驱动开发·python·ci/cd