Last active
March 30, 2016 03:45
-
-
Save jay3686/fba4eafa07b951e459e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.