From f31446fa3183c5801c6da6294e2c9dde1d6bbc35 Mon Sep 17 00:00:00 2001 From: Kelly Slemko Date: Wed, 9 Nov 2011 14:42:10 -0800 Subject: [PATCH 1/2] Added handling for rate limiting error from search api. Now throws special exception which includes number of seconds to wait before trying again. --- twython/twython.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/twython/twython.py b/twython/twython.py index 14b5806..329bfae 100644 --- a/twython/twython.py +++ b/twython/twython.py @@ -93,6 +93,18 @@ class APILimit(TwythonError): def __str__(self): return repr(self.msg) +class RateLimitError(TwythonError): + """ + Raised when you've hit a rate limit. retry_wait_seconds is the number of seconds to + wait before trying again. + """ + def __init__(self, msg, retry_wait_seconds): + self.msg = msg + self.retry_wait_seconds = int(retry_wait_seconds) + + def __str__(self): + return repr(self.msg) + class AuthError(TwythonError): """ @@ -308,6 +320,11 @@ class Twython(object): searchURL = Twython.constructApiURL("http://search.twitter.com/search.json", kwargs) try: resp, content = self.client.request(searchURL, "GET", headers = self.headers) + + if resp.status == 420: + retry_wait_seconds = resp['retry-after'] + raise RateLimitError("getSearchTimeline() is being rate limited. Retry after %s seconds." % retry_wait_seconds, retry_wait_seconds) + return simplejson.loads(content.decode('utf-8')) except HTTPError, e: raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code) From 4d4aa302d469cfe53227d64f1e4ce0bea2f9250d Mon Sep 17 00:00:00 2001 From: Kelly Slemko Date: Wed, 9 Nov 2011 15:39:02 -0800 Subject: [PATCH 2/2] Modifying how error is constructed to make sure it calls init on the super class --- twython/twython.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/twython/twython.py b/twython/twython.py index 329bfae..d8db763 100644 --- a/twython/twython.py +++ b/twython/twython.py @@ -98,9 +98,9 @@ class RateLimitError(TwythonError): Raised when you've hit a rate limit. retry_wait_seconds is the number of seconds to wait before trying again. """ - def __init__(self, msg, retry_wait_seconds): - self.msg = msg + def __init__(self, msg, retry_wait_seconds, error_code): self.retry_wait_seconds = int(retry_wait_seconds) + TwythonError.__init__(self, msg, error_code) def __str__(self): return repr(self.msg) @@ -321,9 +321,12 @@ class Twython(object): try: resp, content = self.client.request(searchURL, "GET", headers = self.headers) - if resp.status == 420: + if int(resp.status) == 420: retry_wait_seconds = resp['retry-after'] - raise RateLimitError("getSearchTimeline() is being rate limited. Retry after %s seconds." % retry_wait_seconds, retry_wait_seconds) + raise RateLimitError("getSearchTimeline() is being rate limited. Retry after %s seconds." % + retry_wait_seconds, + retry_wait_seconds, + resp.status) return simplejson.loads(content.decode('utf-8')) except HTTPError, e: