ratelimiter
This library is considered not test well.
This module provides a way for rate limit and throttle.
We use a pre consume and get left capacity mode. Here is the example:
import time
from pykit import ratelimiter
r = throttle.RateLimiter(100, 200)
# pre consume
r.consume(1000)
# get left capacity
if r.get_stored() < 0:
print "not enough permits"
else:
print "can assign permits is %s" % r.get_stored()
A module that provides a way for rate limit and throttle.
Synopsis:
syntax:
RateLimiter(token_per_second, capacity)
arguments:
-
token_per_second
: specifies the tokens can assign per second. It can be a int, float, long value. If token is 1, it means we can get 1 token per second. -
capacity
specifies the maximum number of tokens that can be saved.
Reduce the permits capacity according to consumed tokens.
syntax:
RateLimiter.consume(consumed,token_time=None)
arguments:
-
consumed
: specifies already consumed tokens. -
token_time
: specifies the time to consume token. Default is None. Iftoken_time
is None, consumed from the latest stored tokens. Iftoken_time
is earlier than last consume time, consumed from stored tokens of last consume time. Iftoken_time
is later than than last consume time, consumed from tokens of thetoken_time
.
return: Nothing.
set the tokens in second.
syntax:
RateLimiter.set_token_per_second(token_per_second)
arguments:
token_per_second
: specifies the tokens per second.
return: Nothing.
set the capacity.
syntax:
RateLimiter.set_capacity(capacity)
arguments:
capacity
: specifies the capacity.
return: Nothing.
get the stored tokens in RateLimiter.
syntax:
RateLimiter.get_stored(token_time=None)
arguments:
token_time
: specifies the time to get for tokens. Default is None. Iftoken_time
is None, return the latest stored tokens. Iftoken_time
is earlier than last consume time,return stored tokens of last consume time. Iftoken_time
is later than than last consume time,return stored tokens of thetoken_time
.
return: the stored tokens in RateLimiter. It can be a negative value for debt.
Tongwei Liu (刘桐伟) [email protected]
The MIT License (MIT)
Copyright (c) 2017 Tongwei Liu (刘桐伟) [email protected]