开源项目推荐|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)
相关推荐
牧歌悠悠1 小时前
【Python 算法】动态规划
python·算法·动态规划
Doris Liu.3 小时前
如何检测代码注入(Part 2)
windows·python·安全·网络安全·网络攻击模型
逢生博客3 小时前
阿里 FunASR 开源中文语音识别大模型应用示例(准确率比faster-whisper高)
人工智能·python·语音识别·funasr
噔噔噔噔@3 小时前
软件测试对于整个行业的重要性及必要性
python·单元测试·压力测试
赵谨言4 小时前
基于Python的Django框架的个人博客管理系统
经验分享·python·毕业设计
Guarding and trust4 小时前
python系统之综合案例:用python打造智能诗词生成助手
服务器·数据库·python
淮北4944 小时前
ros调试工具foxglove使用指南三:在3d空间写写画画(Panel->3D ->Scene entity)
python·学习·3d·机器人
mosquito_lover14 小时前
Python实现音频数字水印方法
python·音视频
苹果.Python.八宝粥4 小时前
Python第七章02:文件读取的练习
开发语言·python
Python之栈4 小时前
Python 3.13 正式支持 iOS:移动开发的新篇章
python·macos·objective-c·cocoa