Skip to content

Instantly share code, notes, and snippets.

@drjackild
Last active October 7, 2021 06:15
Show Gist options
  • Save drjackild/442cc69648704f340a556129eb3d2bc6 to your computer and use it in GitHub Desktop.
Save drjackild/442cc69648704f340a556129eb3d2bc6 to your computer and use it in GitHub Desktop.
import datetime
class Throttle(object):
def __init__(self, domain, max_hits, period):
self.domain = domain
self.max_hits = max_hits
self.hits = 0
self.period = datetime.timedelta(seconds=period)
self.timestamp = datetime.datetime.min
def throttle(self, last_response):
delta = ((self.timestamp + self.period) - last_response).total_seconds()
if delta > 0:
if self.hits < self.max_hits:
self.hits += 1
return delta / (self.max_hits - self.hits)
else:
return delta
else:
self.timestamp = last_response
self.hits = 1
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment