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

相关推荐
小小编程路10 分钟前
Python 还有容器类型互转、进制转换、字符编码转换
开发语言·windows·python
Samooyou41 分钟前
RAG项目案例--02在线检索&过滤流水线
人工智能·python·ai·全文检索·检索
动能小子ohhh1 小时前
DocForge平台的设计与开发--文件上传接口的实现
开发语言·人工智能·python·langchain·ocr·fastapi
ab_dg_dp1 小时前
Android 17+ 提取 AIDL 生成 Java 文件的实用脚本
android·java·python
夏语灬1 小时前
cryptography:Python 密码学标准库的终极选择
开发语言·python·密码学
CTA终结者2 小时前
期货开仓前保证金够吗:get_account 可用与占用字段对照
python·区块链
开源量化GO2 小时前
夜盘白盘衔接几分钟误下单:天勤交易时段与行情过滤
python·区块链
辣椒思密达2 小时前
Python公开数据采集实战:如何解决请求高频拦截与Session会话中断问题
开发语言·python
Albart5753 小时前
Python 实战教程:用 30 分钟学会解决真实问题
开发语言·python
2301_773643623 小时前
ceph池
开发语言·ceph·python