Skip to content

Instantly share code, notes, and snippets.

@jay3686
Last active March 30, 2016 03:45
Show Gist options
  • Save jay3686/fba4eafa07b951e459e4 to your computer and use it in GitHub Desktop.
Save jay3686/fba4eafa07b951e459e4 to your computer and use it in GitHub Desktop.
import time
def rate_limited(num_calls, interval):
minInterval = float(interval) / float(num_calls)
def decorate(func):
lastTimeCalled = [0.0]
def rate_limited_function(*args, **kargs):
elapsed = time.clock() - lastTimeCalled[0]
leftToWait = minInterval - elapsed
if leftToWait > 0 and lastTimeCalled[0] != 0:
time.sleep(leftToWait)
ret = func(*args, **kargs)
lastTimeCalled[0] = time.clock()
return ret
return rate_limited_function
return decorate
@rate_limited(10, 1) # 10 per second at most
def send_event(widget, value):
data = json.dumps({"auth_token": "HUNTER2", "value": value})
widget_url = "http:/example.net:5555/widgets/%s"
res = requests.post(widget_url % widget, data)
print 'sent ', data
return res
import json
import requests
if __name__ == "__main__":
print "Generate some fake ass data for a gauge."
for i in range(1, 101):
send_event('rebillprogress', i)
@jay3686
Copy link
Author

jay3686 commented Mar 30, 2016

Looking at this > a year later... this is client side rate limiting.
Do not copy pasta to globally rate limit an API because it's blocking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment