Skip to content
This repository was archived by the owner on Oct 4, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ RateLimiter

Simple Python module providing rate limiting.

Fork
----
Changes according to the comments in this thread: `https://github.com/RazerM/ratelimiter/issues/15 <https://github.com/RazerM/ratelimiter/issues/15>`_


Overview
--------

Expand Down
11 changes: 7 additions & 4 deletions ratelimiter/_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@ async def __aenter__(self):
# We want to ensure that no more than max_calls were run in the allowed
# period. For this, we store the last timestamps of each call and run
# the rate verification upon each __enter__ call.
if len(self.calls) >= self.max_calls:
until = time.time() + self.period - self._timespan
if self.callback:
asyncio.ensure_future(self.callback(until))

if len(self.calls) == self.max_calls:
until = self.period + self.calls[0]
sleeptime = until - time.time()

if sleeptime > 0:
if self.callback:
asyncio.ensure_future(self.callback(until))

await asyncio.sleep(sleeptime)
return self

Expand Down
18 changes: 11 additions & 7 deletions ratelimiter/_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, max_calls, period=1.0, callback=None):

# We're using a deque to store the last execution timestamps, not for
# its maxlen attribute, but to allow constant time front removal.
self.calls = collections.deque()
self.calls = collections.deque(maxlen=max_calls)

self.period = period
self.max_calls = max_calls
Expand All @@ -49,14 +49,18 @@ def __enter__(self):
# We want to ensure that no more than max_calls were run in the allowed
# period. For this, we store the last timestamps of each call and run
# the rate verification upon each __enter__ call.
if len(self.calls) >= self.max_calls:
until = time.time() + self.period - self._timespan
if self.callback:
t = threading.Thread(target=self.callback, args=(until,))
t.daemon = True
t.start()
if len(self.calls) == self.max_calls:
until = self.period + self.calls[0]
sleeptime = until - time.time()

print('sleeptime', sleeptime, self.calls[0])

if sleeptime > 0:
if self.callback:
t = threading.Thread(target=self.callback, args=(until,))
t.daemon = True
t.start()

time.sleep(sleeptime)
return self

Expand Down