实现说明
令牌桶速率限制器的核心是类 class和函数 __post_init__、allow。
使用要点
allow是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 __post_init__、allow。
签名一览:def allow(self, cost: float = 1.0) -> bool
核心语句
def __post_init__(self) -> None:
self.tokens = self.capacity
self.updated_at = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
now = time.monotonic()
elapsed = now - self.updated_at
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self.updated_at = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False
代码示例
import time
from dataclasses import dataclass, field
@dataclass
class TokenBucket:
capacity: float
refill_rate: float
tokens: float = field(init=False)
updated_at: float = field(init=False)
def __post_init__(self) -> None:
self.tokens = self.capacity
self.updated_at = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
now = time.monotonic()
elapsed = now - self.updated_at
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self.updated_at = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False