-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsync_api.py
43 lines (37 loc) · 1.49 KB
/
Async_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import time
# Allowed is the maximum number of calls to the API allowed over the course of
# interval. interval is in seconds
class ApiManager(object):
def __init__(self, allowed, interval):
self.ncalls = 0
self.last_call = 0
self.queue = []
self.allowed = allowed
self.interval = interval
def call_api(self, cur_input):
print("Api Called: " + cur_input)
def call_on_queue(self):
for val in self.queue:
if self.ncalls < self.allowed:
self.call_asynchronus(self.queue.pop(self.queue.index(val)))
def call_asynchronus(self, cur_input):
if self.last_call == 0:
self.last_call = time.time()
if time.time() - self.last_call < self.interval:
if self.ncalls < self.allowed:
self.call_api(cur_input)
self.ncalls += 1
else:
self.queue.append(cur_input)
while len(self.queue) > 0:
if(time.time() - self.last_call > self.interval):
self.ncalls = 0
self.last_call = time.time()
else:
self.call_on_queue()
if self.ncalls >= self.allowed:
print("time remaining: " + str(60 - (time.time() - self.last_call)))
else:
self.ncalls = 1
self.call_api(cur_input)
self.last_call = time.time()