X-Git-Url: https://jfr.im/git/z_archive/twitter.git/blobdiff_plain/aef72b31d8e84c39435b720f6124db71109e3f9e..e896170126f9b38c3d04c0051fcba34f0a99f6c1:/twitter/api.py diff --git a/twitter/api.py b/twitter/api.py index ad0df9a..570c788 100644 --- a/twitter/api.py +++ b/twitter/api.py @@ -1,6 +1,4 @@ -import urllib2 - -from exceptions import Exception +import urllib.request, urllib.error, urllib.parse from twitter.twitter_globals import POST_ACTIONS from twitter.auth import NoAuth @@ -67,19 +65,22 @@ class TwitterResponse(object): return int(self.headers.getheader('X-RateLimit-Reset')) -# Multiple inheritance makes my inner Java nerd cry. Why can't I just -# add arbitrary attributes to list or str objects?! Guido, we need to -# talk. -class TwitterJsonResponse(TwitterResponse, list): - __doc__ = """Twitter JSON Response - """ + TwitterResponse.__doc__ - def __init__(self, lst, headers): - TwitterResponse.__init__(self, headers) - list.__init__(self, lst) +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 + + class WrappedTwitterResponse(response_typ, TwitterResponse): + __doc__ = TwitterResponse.__doc__ + + def __init__(self, response): + if response_typ is not int: + response_typ.__init__(self, response) + TwitterResponse.__init__(self, headers) + + return WrappedTwitterResponse(response) -class TwitterXmlResponse(TwitterResponse, str): - __doc__ = """Twitter XML Response - """ + TwitterResponse.__doc__ class TwitterCall(object): @@ -109,8 +110,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(unicode(kwargs.pop(uripart, uripart))) - uri = u'/'.join(uriparts) + uriparts.append(str(kwargs.pop(uripart, uripart))) + uri = '/'.join(uriparts) method = "GET" for action in POST_ACTIONS: @@ -143,18 +144,17 @@ class TwitterCall(object): else: body = arg_data - req = urllib2.Request(uriBase, body, headers) + req = urllib.request.Request(uriBase, body, headers) try: - handle = urllib2.urlopen(req) + handle = urllib.request.urlopen(req) if "json" == self.format: - return TwitterJsonResponse(json.loads(handle.read()), - handle.headers) + res = json.loads(handle.read().decode('utf8')) + return wrap_response(res, handle.headers) else: - r = TwitterXmlResponse(handle.read()) - r.headers = handle.headers - return r - except urllib2.HTTPError, e: + return wrap_response( + handle.read().decode('utf8'), handle.headers) + except urllib.error.HTTPError as e: if (e.code == 304): return [] else: @@ -279,5 +279,4 @@ class Twitter(TwitterCall): secure=secure, uriparts=uriparts) -__all__ = ["Twitter", "TwitterError", "TwitterHTTPError", "TwitterJsonResponse", - "TwitterXmlResponse"] +__all__ = ["Twitter", "TwitterError", "TwitterHTTPError", "TwitterResponse"]