开源项目推荐|throttled-py - 支持多种策略及存储选项的 Python 限流库

throttled-py

GitHub: github.com/ZhuoZhuoCra...

简介:🔧 支持多种算法(固定窗口,滑动窗口,令牌桶,漏桶 & GCRA)及存储(Redis、内存)的高性能 Python 限流库。

🚀 功能

  • 提供线程安全的存储后端:Redis(基于 Lua 实现限流算法)、内存(基于 threading.RLock,支持 Key 过期淘汰)。
  • 支持多种限流算法:固定窗口滑动窗口令牌桶漏桶 & 通用信元速率算法(Generic Cell Rate Algorithm, GCRA)
  • 提供灵活的限流策略、配额设置 API,文档详尽。
  • 支持装饰器模式。
  • 良好的性能,单次限流 API 执行耗时换算如下(详见 Benchmarks):
    • 内存:约为 2.5 ~ 4.5 次 dict[key] += 1 操作。
    • Redis:约为 1.06 ~ 1.37 次 INCRBY key increment 操作。

🔰 安装

shell 复制代码
$ pip install throttled-py

🔥 快速开始

1)通用 API

2)样例

python 复制代码
from throttled import RateLimiterType, Throttled, rate_limter, store, utils

throttle = Throttled(
    # 📈 使用令牌桶作为限流算法。
    using=RateLimiterType.TOKEN_BUCKET.value,
    # 🪣 设置配额:每分钟填充 1000 个 Token(limit),桶大小为 1000(burst)。
    quota=rate_limter.per_sec(1_000, burst=1_000),
    # 📁 使用内存作为存储
    store=store.MemoryStore(),
)


def call_api() -> bool:
    # 💧 消耗 Key=/ping 的一个 Token。
    result = throttle.limit("/ping", cost=1)
    return result.limited


if __name__ == "__main__":
    # ✅ Total: 100000, 🕒 Latency: 0.5463 ms/op, 🚀 Throughput: 55630 req/s (--)
    # ❌ Denied: 96314 requests
    benchmark: utils.Benchmark = utils.Benchmark()
    denied_num: int = sum(benchmark.concurrent(call_api, 100_000, workers=32))
    print(f"❌ Denied: {denied_num} requests")

3)作为装饰器

python 复制代码
from throttled import Throttled, rate_limter, exceptions

# 创建一个每分钟允许通过 1 次的限流器。
@Throttled(key="/ping", quota=rate_limter.per_min(1))
def ping() -> str:
    return "ping"

ping()

try:
    ping()
except exceptions.LimitedError as exc:
    # raise Rate limit exceeded: remaining=0, reset_after=60
    print(exc)
    # 在异常中获取限流结果:RateLimitResult(limited=True, state=RateLimitState(limit=1, remaining=0, reset_after=60))
    print(exc.rate_limit_result)
相关推荐
咖啡の猫7 小时前
Python字典推导式
开发语言·python
曹文杰15190301127 小时前
2025 年大模型背景下应用统计本科 计算机方向 培养方案
python·线性代数·机器学习·学习方法
Wulida0099917 小时前
建筑物表面缺陷检测与识别:基于YOLO11-C3k2-Strip模型的智能检测系统
python
FJW0208148 小时前
Python_work4
开发语言·python
爱笑的眼睛118 小时前
从 Seq2Seq 到 Transformer++:深度解构与自构建现代机器翻译核心组件
java·人工智能·python·ai
yaoh.wang8 小时前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
执笔论英雄9 小时前
【RL】slime创建actor的流程
python
吴佳浩 Alben9 小时前
Python入门指南(四)
开发语言·后端·python
小智RE0-走在路上9 小时前
Python学习笔记(8) --函数的多返回值,不同传参,匿名函数
笔记·python·学习
ZHSH.9 小时前
2026蓝桥杯备赛 | 赛事介绍及python基础(未完)
python·蓝桥杯·数据结构与算法