Created
May 22, 2020 12:42
-
-
Save tomchristie/4f8f94d09b9b7fe70017c28b0acf3b89 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class ThrottleTransport: | |
def __init__(self, throttle, **kwargs): | |
self.pool = httpcore.SyncConnectionPool(**kwargs) | |
self.history = [] | |
# Parse the thottle, which should be a string, like '100/minute'. | |
count, _, duration = throttle.partition('/') | |
self.max_in_history = int(count) | |
self.cutoff = {'second': 1.0, 'minute': 60.0, 'hour': 3600.0}[duration] | |
def request(method, url, headers, stream, timeout): | |
now = time.time() | |
while len(self.history) >= self.max_in_history: | |
expiry = now - self.cutoff | |
# Expiry old entries in the history. | |
self.history = [timestamp for timestamp in self.history if timestamp > expiry] | |
# Sleep for a bit if we've exceeded the throttle rate. | |
if len(self.history) >= self.max_in_history: | |
time.sleep(0.1) | |
now = time.time() | |
self.history.append(now) | |
return self.pool.request(method, url, headers, stream, timeout) | |
def close(self): | |
self.pool.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment