Skip to content

Instantly share code, notes, and snippets.

@kodekracker
Last active September 4, 2017 07:51
Show Gist options
  • Select an option

  • Save kodekracker/2ca99f5783ebc673305849182b5a146f to your computer and use it in GitHub Desktop.

Select an option

Save kodekracker/2ca99f5783ebc673305849182b5a146f to your computer and use it in GitHub Desktop.
import time
def rate_limiter(period, damping = 1.0):
"""
Prevent a method from being called if it was previously called before
a time widows has elapsed.
:param period: The time window after which method invocations can continue
:param damping: A factor by which to dampen the time window.
:return function: Decorated function that will forward method invocations if the time window has elapsed.
"""
frequency = damping / float(period)
def decorate(func):
last_time_called = [0.0]
def rate_limited_function(*args, **kargs):
elapsed = time.clock() - last_time_called[0]
left_to_wait = frequency - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
ret = func(*args, **kargs)
last_time_called[0] = time.clock()
return ret
return rate_limited_function
return decorate
# Usage
# Assume we have rate limit below func , like max 10 call per second for that method
@rate_limiter(10)
def func(i):
# do something here, which you want to rate limit it like third party apis
# calling which have a very strict rules to send no of requests within a
# given time frame (like, 10 requests per second)
res = 'RESULT HERE'
print 'Running %s' % i
return res
if __name__ == "__main__":
for i in range(0, 20):
func(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment