Add throttling to clientpy3.py
authorkaliko <kaliko.jack@azylum.org>
Sat, 5 Jan 2013 13:07:59 +0000 (14:07 +0100)
committerkaliko <kaliko.jack@azylum.org>
Sat, 5 Jan 2013 13:07:59 +0000 (14:07 +0100)
misc/clientpy3.py

index a8c9398..e1dab9b 100755 (executable)
@@ -12,6 +12,25 @@ import urllib.parse
 
 from time import time
 from urllib.error import URLError, HTTPError
+from datetime import datetime, timedelta
+
+
+WAIT_BETWEEN_REQUESTS = timedelta(0, 0.9)
+
+
+class Throttle(object):
+    def __init__(self, wait):
+        self.wait = wait
+        self.last_called = datetime.now()
+
+    def __call__(self, func):
+        def wrapper(*args, **kwargs):
+            while self.last_called + self.wait > datetime.now():
+                sleep(0.2)
+            result = func(*args, **kwargs)
+            self.last_called = datetime.now()
+            return result
+        return wrapper
 
 
 class Track(object):
@@ -52,6 +71,7 @@ def get_api_options(track):
             options[v] = track.__getattribute__(k)
     return options
 
+@Throttle(WAIT_BETWEEN_REQUESTS)
 def scrobble(trk=None, user=None, pwd=None, srv=None):
     sc_url = 'http://{server}/api/{user}/scrobbles/'
     url = sc_url.format(user=user, server=srv)