1 # Written by Andrea Reale
2 # see LICENSE.txt for license information
7 class SimpleTokenBucket(object):
9 A simple implementation of a token bucket, to
10 control the rate of subtitles being uploaded.
12 1 token corresponds to 1 KB
17 def __init__(self, fill_rate, capacity = -1):
19 Creates a token bucket initialy having 0 tokens,
20 with the given fill_rate.
22 @param fill_rate: number of tokens refilled per second.
23 a token corrisponds to 1KB
24 @param capacity: maximum number of tokens in the bucket.
27 #infinite bucket! (well, really big at least)
29 capacity = 2**30 # 1 TeraByte capacity
30 self.capacity = float(capacity)
32 self._tokens = float(0)
34 self.fill_rate = float(fill_rate)
35 self.timestamp = time()
37 def consume(self, tokens):
38 """Consume tokens from the bucket. Returns True if there were
39 sufficient tokens otherwise False."""
40 if tokens <= self.tokens:
41 self._tokens -= tokens
46 def _consume_all(self):
48 Consumes every token in the bucket
50 self._tokens = float(0)
54 if self._tokens < self.capacity:
56 delta = self.fill_rate * (now - self.timestamp)
57 self._tokens = min(self.capacity, self._tokens + delta)
62 def upload_rate(self):