other.token_bucket ================== .. py:module:: other.token_bucket .. autoapi-nested-parse:: Implementation of the Token Bucket Algorithm Token `rate` is added to the bucket every `frequency` seconds. The bucket can hold tokens up to `capacity` (full). The bucket starts full. Each request consumes one token. If a token arrives when the bucket is full, the token is discarded. If a request arrives when the bucket is empty, it is discarded. If the bucket has tokens available, requests will pass. https://en.wikipedia.org/wiki/Token_bucket Attributes ---------- .. autoapisummary:: other.token_bucket.bucket Classes ------- .. autoapisummary:: other.token_bucket.TokenBucketRateLimiter Module Contents --------------- .. py:class:: TokenBucketRateLimiter(rate: int, capacity: int, frequency: int) .. py:method:: _add_tokens() -> None Refill tokens only when a full minute has passed. >>> bucket = TokenBucketRateLimiter(1, 4, 60) >>> bucket.tokens # Initially has a rate of 4 tokens 4 >>> bucket._add_tokens() >>> bucket.tokens # Bucket already full 4 .. py:method:: allow_request() -> bool Check if a request is allowed. If there are enough tokens, it consumes one token. :return: True if the request is allowed, False otherwise. >>> bucket = TokenBucketRateLimiter(1, 2, 60) >>> bucket.allow_request() # Token is available, request passes True >>> bucket.allow_request() # Token is available, request passes True >>> bucket.allow_request() # No token left, request is dropped False .. py:attribute:: capacity .. py:attribute:: frequency .. py:attribute:: last_checked .. py:attribute:: lock .. py:attribute:: rate .. py:attribute:: tokens .. py:data:: bucket