Merge 4553e273c7 into 449a71daf8
This commit is contained in:
commit
28d4891eb8
1 changed files with 69 additions and 87 deletions
|
|
@ -11,16 +11,10 @@
|
||||||
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
|
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
|
||||||
__version__ = "1.4.6"
|
__version__ = "1.4.6"
|
||||||
|
|
||||||
import cgi
|
|
||||||
import urllib
|
import urllib
|
||||||
import urllib2
|
import urllib2
|
||||||
import urlparse
|
|
||||||
import httplib
|
|
||||||
import httplib2
|
import httplib2
|
||||||
import mimetypes
|
|
||||||
import mimetools
|
|
||||||
import re
|
import re
|
||||||
import inspect
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
@ -55,40 +49,27 @@ except ImportError:
|
||||||
# Seriously wtf is wrong with you if you get this Exception.
|
# Seriously wtf is wrong with you if you get this Exception.
|
||||||
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
|
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
|
||||||
|
|
||||||
# Try and gauge the old OAuth2 library spec. Versions 1.5 and greater no longer have the callback
|
|
||||||
# url as part of the request object; older versions we need to patch for Python 2.5... ugh. ;P
|
|
||||||
OAUTH_CALLBACK_IN_URL = False
|
|
||||||
OAUTH_LIB_SUPPORTS_CALLBACK = False
|
|
||||||
if not hasattr(oauth, '_version') or float(oauth._version.manual_verstr) <= 1.4:
|
|
||||||
OAUTH_CLIENT_INSPECTION = inspect.getargspec(oauth.Client.request)
|
|
||||||
try:
|
|
||||||
OAUTH_LIB_SUPPORTS_CALLBACK = 'callback_url' in OAUTH_CLIENT_INSPECTION.args
|
|
||||||
except AttributeError:
|
|
||||||
# Python 2.5 doesn't return named tuples, so don't look for an args section specifically.
|
|
||||||
OAUTH_LIB_SUPPORTS_CALLBACK = 'callback_url' in OAUTH_CLIENT_INSPECTION
|
|
||||||
else:
|
|
||||||
OAUTH_CALLBACK_IN_URL = True
|
|
||||||
|
|
||||||
class TwythonError(AttributeError):
|
class TwythonError(AttributeError):
|
||||||
"""
|
"""
|
||||||
Generic error class, catch-all for most Twython issues.
|
Generic error class, catch-all for most Twython issues.
|
||||||
Special cases are handled by APILimit and AuthError.
|
Special cases are handled by TwythonAPILimit and TwythonAuthError.
|
||||||
|
|
||||||
Note: To use these, the syntax has changed as of Twython 1.3. To catch these,
|
Note: To use these, the syntax has changed as of Twython 1.3. To catch these,
|
||||||
you need to explicitly import them into your code, e.g:
|
you need to explicitly import them into your code, e.g:
|
||||||
|
|
||||||
from twython import TwythonError, APILimit, AuthError
|
from twython import TwythonError, TwythonAPILimit, TwythonAuthError
|
||||||
"""
|
"""
|
||||||
def __init__(self, msg, error_code=None):
|
def __init__(self, msg, error_code=None):
|
||||||
self.msg = msg
|
self.msg = msg
|
||||||
if error_code == 400:
|
if error_code == 400:
|
||||||
raise APILimit(msg)
|
raise TwythonAPILimit(msg)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return repr(self.msg)
|
return repr(self.msg)
|
||||||
|
|
||||||
|
|
||||||
class APILimit(TwythonError):
|
class TwythonAPILimit(TwythonError):
|
||||||
"""
|
"""
|
||||||
Raised when you've hit an API limit. Try to avoid these, read the API
|
Raised when you've hit an API limit. Try to avoid these, read the API
|
||||||
docs if you're running into issues here, Twython does not concern itself with
|
docs if you're running into issues here, Twython does not concern itself with
|
||||||
|
|
@ -100,7 +81,8 @@ class APILimit(TwythonError):
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return repr(self.msg)
|
return repr(self.msg)
|
||||||
|
|
||||||
class RateLimitError(TwythonError):
|
|
||||||
|
class TwythonRateLimitError(TwythonError):
|
||||||
"""
|
"""
|
||||||
Raised when you've hit a rate limit. retry_wait_seconds is the number of seconds to
|
Raised when you've hit a rate limit. retry_wait_seconds is the number of seconds to
|
||||||
wait before trying again.
|
wait before trying again.
|
||||||
|
|
@ -113,7 +95,7 @@ class RateLimitError(TwythonError):
|
||||||
return repr(self.msg)
|
return repr(self.msg)
|
||||||
|
|
||||||
|
|
||||||
class AuthError(TwythonError):
|
class TwythonAuthError(TwythonError):
|
||||||
"""
|
"""
|
||||||
Raised when you try to access a protected resource and it fails due to some issue with
|
Raised when you try to access a protected resource and it fails due to some issue with
|
||||||
your authentication.
|
your authentication.
|
||||||
|
|
@ -126,7 +108,8 @@ class AuthError(TwythonError):
|
||||||
|
|
||||||
|
|
||||||
class Twython(object):
|
class Twython(object):
|
||||||
def __init__(self, twitter_token = None, twitter_secret = None, oauth_token = None, oauth_token_secret = None, headers=None, callback_url=None, client_args={}):
|
def __init__(self, twitter_token=None, twitter_secret=None, oauth_token=None, oauth_token_secret=None, \
|
||||||
|
headers=None, client_args=None):
|
||||||
"""setup(self, oauth_token = None, headers = None)
|
"""setup(self, oauth_token = None, headers = None)
|
||||||
|
|
||||||
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
|
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
|
||||||
|
|
@ -140,7 +123,8 @@ class Twython(object):
|
||||||
headers - User agent header, dictionary style ala {'User-Agent': 'Bert'}
|
headers - User agent header, dictionary style ala {'User-Agent': 'Bert'}
|
||||||
client_args - additional arguments for HTTP client (see httplib2.Http.__init__), e.g. {'timeout': 10.0}
|
client_args - additional arguments for HTTP client (see httplib2.Http.__init__), e.g. {'timeout': 10.0}
|
||||||
|
|
||||||
** Note: versioning is not currently used by search.twitter functions; when Twitter moves their junk, it'll be supported.
|
** Note: versioning is not currently used by search.twitter functions;
|
||||||
|
when Twitter moves their junk, it'll be supported.
|
||||||
"""
|
"""
|
||||||
# Needed for hitting that there API.
|
# Needed for hitting that there API.
|
||||||
self.request_token_url = 'http://twitter.com/oauth/request_token'
|
self.request_token_url = 'http://twitter.com/oauth/request_token'
|
||||||
|
|
@ -151,7 +135,6 @@ class Twython(object):
|
||||||
self.twitter_secret = twitter_secret
|
self.twitter_secret = twitter_secret
|
||||||
self.oauth_token = oauth_token
|
self.oauth_token = oauth_token
|
||||||
self.oauth_secret = oauth_token_secret
|
self.oauth_secret = oauth_token_secret
|
||||||
self.callback_url = callback_url
|
|
||||||
|
|
||||||
# If there's headers, set them, otherwise be an embarassing parent for their own good.
|
# If there's headers, set them, otherwise be an embarassing parent for their own good.
|
||||||
self.headers = headers
|
self.headers = headers
|
||||||
|
|
@ -161,6 +144,8 @@ class Twython(object):
|
||||||
self.consumer = None
|
self.consumer = None
|
||||||
self.token = None
|
self.token = None
|
||||||
|
|
||||||
|
client_args = client_args or {}
|
||||||
|
|
||||||
if self.twitter_token is not None and self.twitter_secret is not None:
|
if self.twitter_token is not None and self.twitter_secret is not None:
|
||||||
self.consumer = oauth.Consumer(self.twitter_token, self.twitter_secret)
|
self.consumer = oauth.Consumer(self.twitter_token, self.twitter_secret)
|
||||||
|
|
||||||
|
|
@ -176,6 +161,7 @@ class Twython(object):
|
||||||
# If they don't do authentication, but still want to request unprotected resources, we need an opener.
|
# If they don't do authentication, but still want to request unprotected resources, we need an opener.
|
||||||
self.client = httplib2.Http(**client_args)
|
self.client = httplib2.Http(**client_args)
|
||||||
# register available funcs to allow listing name when debugging.
|
# register available funcs to allow listing name when debugging.
|
||||||
|
|
||||||
def setFunc(key):
|
def setFunc(key):
|
||||||
return lambda **kwargs: self._constructFunc(key, **kwargs)
|
return lambda **kwargs: self._constructFunc(key, **kwargs)
|
||||||
for key in api_table.keys():
|
for key in api_table.keys():
|
||||||
|
|
@ -210,34 +196,19 @@ class Twython(object):
|
||||||
|
|
||||||
Returns an authorization URL for a user to hit.
|
Returns an authorization URL for a user to hit.
|
||||||
"""
|
"""
|
||||||
callback_url = self.callback_url or 'oob'
|
|
||||||
|
|
||||||
request_args = {}
|
request_args = {}
|
||||||
if OAUTH_LIB_SUPPORTS_CALLBACK:
|
|
||||||
request_args['callback_url'] = callback_url
|
|
||||||
|
|
||||||
resp, content = self.client.request(self.request_token_url, "GET", **request_args)
|
resp, content = self.client.request(self.request_token_url, "GET", **request_args)
|
||||||
|
|
||||||
if resp['status'] != '200':
|
if resp['status'] != '200':
|
||||||
raise AuthError("Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s" % (resp['status'], content))
|
raise TwythonAuthError("Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s" % (resp['status'], content))
|
||||||
|
|
||||||
request_tokens = dict(parse_qsl(content))
|
request_tokens = dict(parse_qsl(content))
|
||||||
|
|
||||||
oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed')=='true'
|
|
||||||
|
|
||||||
if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob' and oauth_callback_confirmed:
|
|
||||||
import warnings
|
|
||||||
warnings.warn("oauth2 library doesn't support OAuth 1.0a type callback, but remote requires it")
|
|
||||||
oauth_callback_confirmed = False
|
|
||||||
|
|
||||||
auth_url_params = {
|
auth_url_params = {
|
||||||
'oauth_token': request_tokens['oauth_token'],
|
'oauth_token': request_tokens['oauth_token'],
|
||||||
}
|
}
|
||||||
|
|
||||||
# Use old-style callback argument
|
|
||||||
if OAUTH_CALLBACK_IN_URL or (callback_url!='oob' and not oauth_callback_confirmed):
|
|
||||||
auth_url_params['oauth_callback'] = callback_url
|
|
||||||
|
|
||||||
request_tokens['auth_url'] = self.authenticate_url + '?' + urllib.urlencode(auth_url_params)
|
request_tokens['auth_url'] = self.authenticate_url + '?' + urllib.urlencode(auth_url_params)
|
||||||
|
|
||||||
return request_tokens
|
return request_tokens
|
||||||
|
|
@ -275,7 +246,7 @@ class Twython(object):
|
||||||
content = urllib2.urlopen(shortener + "?" + urllib.urlencode({query: Twython.unicode2utf8(url_to_shorten)})).read()
|
content = urllib2.urlopen(shortener + "?" + urllib.urlencode({query: Twython.unicode2utf8(url_to_shorten)})).read()
|
||||||
return content
|
return content
|
||||||
except HTTPError, e:
|
except HTTPError, e:
|
||||||
raise TwythonError("shortenURL() failed with a %s error code." % `e.code`)
|
raise TwythonError("shortenURL() failed with a %s error code." % e.code)
|
||||||
|
|
||||||
def bulkUserLookup(self, ids=None, screen_names=None, version=1, **kwargs):
|
def bulkUserLookup(self, ids=None, screen_names=None, version=1, **kwargs):
|
||||||
""" bulkUserLookup(self, ids = None, screen_names = None, version = 1, **kwargs)
|
""" bulkUserLookup(self, ids = None, screen_names = None, version = 1, **kwargs)
|
||||||
|
|
@ -295,7 +266,7 @@ class Twython(object):
|
||||||
resp, content = self.client.request(lookupURL, "POST", headers=self.headers)
|
resp, content = self.client.request(lookupURL, "POST", headers=self.headers)
|
||||||
return simplejson.loads(content.decode('utf-8'))
|
return simplejson.loads(content.decode('utf-8'))
|
||||||
except HTTPError, e:
|
except HTTPError, e:
|
||||||
raise TwythonError("bulkUserLookup() failed with a %s error code." % `e.code`, e.code)
|
raise TwythonError("bulkUserLookup() failed with a %s error code." % e.code, e.code)
|
||||||
|
|
||||||
def search(self, **kwargs):
|
def search(self, **kwargs):
|
||||||
"""search(search_query, **kwargs)
|
"""search(search_query, **kwargs)
|
||||||
|
|
@ -313,14 +284,14 @@ class Twython(object):
|
||||||
|
|
||||||
if int(resp.status) == 420:
|
if int(resp.status) == 420:
|
||||||
retry_wait_seconds = resp['retry-after']
|
retry_wait_seconds = resp['retry-after']
|
||||||
raise RateLimitError("getSearchTimeline() is being rate limited. Retry after %s seconds." %
|
raise TwythonRateLimitError("getSearchTimeline() is being rate limited. Retry after %s seconds." %
|
||||||
retry_wait_seconds,
|
retry_wait_seconds,
|
||||||
retry_wait_seconds,
|
retry_wait_seconds,
|
||||||
resp.status)
|
resp.status)
|
||||||
|
|
||||||
return simplejson.loads(content.decode('utf-8'))
|
return simplejson.loads(content.decode('utf-8'))
|
||||||
except HTTPError, e:
|
except HTTPError, e:
|
||||||
raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code)
|
raise TwythonError("getSearchTimeline() failed with a %s error code." % e.code, e.code)
|
||||||
|
|
||||||
def searchTwitter(self, **kwargs):
|
def searchTwitter(self, **kwargs):
|
||||||
"""use search() ,this is a fall back method to support searchTwitter()
|
"""use search() ,this is a fall back method to support searchTwitter()
|
||||||
|
|
@ -343,7 +314,7 @@ class Twython(object):
|
||||||
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
|
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
|
||||||
data = simplejson.loads(content.decode('utf-8'))
|
data = simplejson.loads(content.decode('utf-8'))
|
||||||
except HTTPError, e:
|
except HTTPError, e:
|
||||||
raise TwythonError("searchGen() failed with a %s error code." % `e.code`, e.code)
|
raise TwythonError("searchGen() failed with a %s error code." % e.code, e.code)
|
||||||
|
|
||||||
if not data['results']:
|
if not data['results']:
|
||||||
raise StopIteration
|
raise StopIteration
|
||||||
|
|
@ -362,7 +333,7 @@ class Twython(object):
|
||||||
raise TwythonError("searchGen() exited because page takes str")
|
raise TwythonError("searchGen() exited because page takes str")
|
||||||
except e:
|
except e:
|
||||||
raise TwythonError("searchGen() failed with %s error code" % \
|
raise TwythonError("searchGen() failed with %s error code" % \
|
||||||
`e.code`, e.code)
|
e.code, e.code)
|
||||||
|
|
||||||
for tweet in self.searchGen(search_query, **kwargs):
|
for tweet in self.searchGen(search_query, **kwargs):
|
||||||
yield tweet
|
yield tweet
|
||||||
|
|
@ -386,7 +357,7 @@ class Twython(object):
|
||||||
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
|
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
resp, content = self.client.request("http://api.twitter.com/%d/%s/%s/members/%s.json" % (version, username, list_id, `id`), headers = self.headers)
|
resp, content = self.client.request("http://api.twitter.com/%d/%s/%s/members/%s.json" % (version, username, list_id, id), headers=self.headers)
|
||||||
return simplejson.loads(content.decode('utf-8'))
|
return simplejson.loads(content.decode('utf-8'))
|
||||||
except HTTPError, e:
|
except HTTPError, e:
|
||||||
raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code)
|
raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code)
|
||||||
|
|
@ -405,7 +376,7 @@ class Twython(object):
|
||||||
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
|
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
resp, content = self.client.request("http://api.twitter.com/%d/%s/%s/following/%s.json" % (version, username, list_id, `id`), headers = self.headers)
|
resp, content = self.client.request("http://api.twitter.com/%d/%s/%s/following/%s.json" % (version, username, list_id, id), headers=self.headers)
|
||||||
return simplejson.loads(content.decode('utf-8'))
|
return simplejson.loads(content.decode('utf-8'))
|
||||||
except HTTPError, e:
|
except HTTPError, e:
|
||||||
raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code)
|
raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code)
|
||||||
|
|
@ -466,7 +437,6 @@ class Twython(object):
|
||||||
req = requests.post(url, data=params, files=file_, headers=self.headers)
|
req = requests.post(url, data=params, files=file_, headers=self.headers)
|
||||||
return req.content
|
return req.content
|
||||||
|
|
||||||
|
|
||||||
def getProfileImageUrl(self, username, size=None, version=1):
|
def getProfileImageUrl(self, username, size=None, version=1):
|
||||||
""" getProfileImageUrl(username)
|
""" getProfileImageUrl(username)
|
||||||
|
|
||||||
|
|
@ -506,3 +476,15 @@ class Twython(object):
|
||||||
if isinstance(text, (str, unicode)):
|
if isinstance(text, (str, unicode)):
|
||||||
return Twython.unicode2utf8(text)
|
return Twython.unicode2utf8(text)
|
||||||
return str(text)
|
return str(text)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
t = Twython('OZpEzBbXBin6U0BnZNBTQ', 'PyK5bJG68qDkVBtI5xTghkY1BvQvZTB2JtlqxJjzE')
|
||||||
|
req_tokens = t.get_authentication_tokens()
|
||||||
|
oauth_secret = req_tokens['oauth_token_secret']
|
||||||
|
print 'Go to %s' % req_tokens['auth_url']
|
||||||
|
|
||||||
|
oauth_token = raw_input('OAuth Token: ')
|
||||||
|
|
||||||
|
t = Twython('OZpEzBbXBin6U0BnZNBTQ', 'PyK5bJG68qDkVBtI5xTghkY1BvQvZTB2JtlqxJjzE', oauth_token, oauth_secret)
|
||||||
|
final_tokens = t.get_authorized_tokens()
|
||||||
|
print final_tokens
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue