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

相关推荐
亿牛云爬虫专家几秒前
爬虫调度系统设计:用 Celery 实现按媒体权重动态调整的抓取频率控制
爬虫·python·隧道代理·舆情采集·媒体权重·频率控制·ip自动轮换
Code额1 小时前
Python 连接 DeepSeek API,OpenAI
开发语言·python·ai·ai编程
Suhan422 小时前
SQLAlchemy的两种查询query()查询、stmt=select()查询
数据库·python·sql·oracle
AAA@峥2 小时前
Python 基础开篇:认识 Python、版本选择、环境部署与首个 HelloWorld
开发语言·python
Metaphor6922 小时前
使用 Python 快速在 Word 文档中插入图片
python·word
2601_966871402 小时前
Python 爬虫 + 数据挖掘实战:数据抓取与深度挖掘分析全流程
爬虫·python·数据挖掘
青禾8373 小时前
Linux 系统信息、权限管理与 Python 并发编程(协程与线程)完全指南
linux·python
曲无忆3 小时前
密码学三大核心技术解析
python·密码学
qq21084629533 小时前
在python中什么是 self 和 cls?
开发语言·前端·python