+
16
-

python有没有好用的限流库?

python有没有好用的限流库?


网友回复

+
24
-

Python 中有几个实用的限流库,以下是一些推荐选项及其特点:

throttled-py

这是一个轻量且灵活的限流库,支持多种限流算法(如固定窗口、滑动窗口、令牌桶、漏桶和 GCRA),适配 Redis 存储后端,同时支持同步和异步场景。它还提供线程安全的存储后端(如内存和 Redis),支持配置限流策略及等待重试模式。

安装

pip install throttled-py

使用示例(简单版)

以下是一个使用 内存存储 + 令牌桶算法 的基本限流示例:示例 1:限制每秒最多处理 3 次请求

from throttled_py.memory import MemoryStore
from throttled_py.limiter import RateLimiter
from throttled_py.strategy.token_bucket import TokenBucket

# 存储方式:内存
store = MemoryStore()

# 创建限流策略:每秒最多 3 次
strategy = TokenBucket(rate=3, capacity=3)

# 创建限流器
limiter = RateLimiter(store=store, strategy=strategy)

# 模拟请求
for i in range(5):
  ...

点击查看剩余70%

我知道答案,我要回答