开源项目推荐|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)
相关推荐
Scott9999HH7 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
AI云海8 小时前
python 列表、元组、集合和字典
开发语言·python
二十雨辰8 小时前
[爬虫]-Urllib
爬虫·python
玉鸯10 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_4462608511 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao11 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
qetfw11 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
用户83562907805112 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
一次旅行12 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化