X-Git-Url: https://jfr.im/git/z_archive/twitter.git/blobdiff_plain/aec689591a6382c274aeedcd4f4a89762f2f1f17..abddd41987c3993efd3dbc9cd1f6f2b6dd5a9751:/twitter/api.py diff --git a/twitter/api.py b/twitter/api.py index 5d75f87..c46b52d 100644 --- a/twitter/api.py +++ b/twitter/api.py @@ -39,6 +39,47 @@ class TwitterHTTPError(TwitterError): self.e.code, self.uri, self.format, self.uriparts, self.e.fp.read())) +class TwitterResponse(object): + """ + Response from a twitter request. Behaves like a list or a string + (depending on requested format) but it has a few other interesting + attributes. + + `headers` gives you access to the response headers as an + httplib.HTTPHeaders instance. You can do + `response.headers.getheader('h')` to retrieve a header. + """ + def __init__(self, headers): + self.headers = headers + + @property + def rate_limit_remaining(self): + """ + Remaining requests in the current rate-limit. + """ + return int(self.headers.getheader('X-RateLimit-Remaining')) + + @property + def rate_limit_reset(self): + """ + Time in UTC epoch seconds when the rate limit will reset. + """ + return int(self.headers.getheader('X-RateLimit-Reset')) + + +def wrap_response(response, headers): + response_typ = type(response) + class WrappedTwitterResponse(TwitterResponse, response_typ): + __doc__ = TwitterResponse.__doc__ + + def __init__(self, response, headers): + response_typ.__init__(self, response) + TwitterResponse.__init__(self, headers) + + return WrappedTwitterResponse(response, headers) + + + class TwitterCall(object): def __init__( self, auth, format, domain, uri="", agent=None, @@ -66,8 +107,8 @@ class TwitterCall(object): for uripart in self.uriparts: # If this part matches a keyword argument, use the # supplied value otherwise, just use the part. - uriparts.append(kwargs.pop(uripart, uripart)) - uri = '/'.join(uriparts) + uriparts.append(unicode(kwargs.pop(uripart, uripart))) + uri = u'/'.join(uriparts) method = "GET" for action in POST_ACTIONS: @@ -105,9 +146,10 @@ class TwitterCall(object): try: handle = urllib2.urlopen(req) if "json" == self.format: - return json.loads(handle.read()) + res = json.loads(handle.read()) + return wrap_response(res, handle.headers) else: - return handle.read() + return wrap_response(handle.read(), handle.headers) except urllib2.HTTPError, e: if (e.code == 304): return [] @@ -233,4 +275,4 @@ class Twitter(TwitterCall): secure=secure, uriparts=uriparts) -__all__ = ["Twitter", "TwitterError", "TwitterHTTPError"] +__all__ = ["Twitter", "TwitterError", "TwitterHTTPError", "TwitterResponse"]