+class TwitterHTTPError(TwitterError):
+ """
+ Exception thrown by the Twitter object when there is an
+ HTTP error interacting with twitter.com.
+ """
+ def __init__(self, e, uri, format, uriparts):
+ self.e = e
+ self.uri = uri
+ self.format = format
+ self.uriparts = uriparts
+ try:
+ data = self.e.fp.read()
+ except http_client.IncompleteRead as e:
+ # can't read the error text
+ # let's try some of it
+ data = e.partial
+ if self.e.headers.get('Content-Encoding') == 'gzip':
+ buf = StringIO(data)
+ f = gzip.GzipFile(fileobj=buf)
+ self.response_data = f.read()
+ else:
+ self.response_data = data
+ super(TwitterHTTPError, self).__init__(str(self))
+
+ def __str__(self):
+ fmt = ("." + self.format) if self.format else ""
+ return (
+ "Twitter sent status %i for URL: %s%s using parameters: "
+ "(%s)\ndetails: %s" %(
+ self.e.code, self.uri, fmt, self.uriparts,
+ self.response_data))
+
+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.get('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.get('X-Rate-Limit-Remaining', "0"))
+
+ @property
+ def rate_limit_limit(self):
+ """
+ The rate limit ceiling for that given request.
+ """
+ return int(self.headers.get('X-Rate-Limit-Limit', "0"))
+
+ @property
+ def rate_limit_reset(self):
+ """
+ Time in UTC epoch seconds when the rate limit will reset.
+ """
+ return int(self.headers.get('X-Rate-Limit-Reset', "0"))
+
+
+def wrap_response(response, headers):
+ response_typ = type(response)
+ if response_typ is bool:
+ # HURF DURF MY NAME IS PYTHON AND I CAN'T SUBCLASS bool.
+ response_typ = int
+ elif response_typ is str:
+ return response
+
+ class WrappedTwitterResponse(response_typ, TwitterResponse):
+ __doc__ = TwitterResponse.__doc__
+
+ def __init__(self, response, headers):
+ response_typ.__init__(self, response)
+ TwitterResponse.__init__(self, headers)
+ def __new__(cls, response, headers):
+ return response_typ.__new__(cls, response)
+
+ return WrappedTwitterResponse(response, headers)
+
+
+