HelloGitHub 第 110 期
开箱即用的 Python 限流库。这是一款轻量且灵活的 Python 限流库,同步/异步皆可用。它支持多种限流算法,包括固定窗口、滑动窗口、令牌桶、漏桶和 GCRA,适配 Redis 存储后端,并提供函数、装饰器和上下文管理器等多种灵活用法。
from throttled import RateLimiterType, Throttled, rate_limiter, store, utils throttle = Throttled( # 📈 Use Token Bucket algorithm using=RateLimiterType.TOKEN_BUCKET.value, # 🪣 Set quota: 1,000 tokens per second (limit), bucket size 1,000 (burst) quota=rate_limiter.per_sec(1_000, burst=1_000), # 📁 Use In-Memory storage store=store.MemoryStore(), ) def call_api() -> bool: # 💧 Deduct 1 token for key="/ping" result = throttle.limit("/ping", cost=1) return result.limited if __name__ == "__main__": # 💻 Python 3.12.10, Linux 5.4.119-1-tlinux4-0009.1, Arch: x86_64, Specs: 2C4G. # ✅ Total: 100000, 🕒 Latency: 0.0068 ms/op, 🚀 Throughput: 122513 req/s (--) # ❌ Denied: 98000 requests benchmark: utils.Benchmark = utils.Benchmark() denied_num: int = sum(benchmark.serial(call_api, 100_000)) print(f"❌ Denied: {denied_num} requests")
内容来自 HelloGitHub 月刊,版权归原作者所有。
阅读原文 ↗