This commit is contained in:
GitHub Merge Button 2011-08-30 10:26:55 -07:00
commit 71d02b166f
6 changed files with 443 additions and 368 deletions

5
.idea/encodings.xml generated Normal file
View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
</project>

8
.idea/misc.xml generated Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DependencyValidationManager">
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.1 (C:/projects/critiqus/environment/Scripts/python.exe)" project-jdk-type="Python SDK" />
</project>

9
.idea/modules.xml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/twython.iml" filepath="$PROJECT_DIR$/.idea/twython.iml" />
</modules>
</component>
</project>

9
.idea/twython.iml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

7
.idea/vcs.xml generated Normal file
View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View file

@ -46,7 +46,8 @@ except ImportError:
from django.utils import simplejson from django.utils import simplejson
except: except:
# 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 # 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 # url as part of the request object; older versions we need to patch for Python 2.5... ugh. ;P
@ -72,6 +73,7 @@ class TwythonError(AttributeError):
from twython import TwythonError, APILimit, AuthError from twython import TwythonError, APILimit, AuthError
""" """
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:
@ -87,6 +89,7 @@ class APILimit(TwythonError):
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
this matter beyond telling you that you've done goofed. this matter beyond telling you that you've done goofed.
""" """
def __init__(self, msg): def __init__(self, msg):
self.msg = msg self.msg = msg
@ -99,6 +102,7 @@ class AuthError(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.
""" """
def __init__(self, msg): def __init__(self, msg):
self.msg = msg self.msg = msg
@ -107,7 +111,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,
callback_url=None, client_args={}):
"""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).
@ -173,21 +178,24 @@ class Twython(object):
I'll hate myself for saying this, but this is heavily inspired by Ruby's "method_missing". I'll hate myself for saying this, but this is heavily inspired by Ruby's "method_missing".
""" """
def get(self, **kwargs): def get(self, **kwargs):
# Go through and replace any mustaches that are in our API url. # Go through and replace any mustaches that are in our API url.
fn = api_table[api_call] fn = api_table[api_call]
base = re.sub( base = re.sub(
'\{\{(?P<m>[a-zA-Z_]+)\}\}', '\{\{(?P<m>[a-zA-Z_]+)\}\}',
lambda m: "%s" % kwargs.get(m.group(1), '1'), # The '1' here catches the API version. Slightly hilarious. lambda m: "%s" % kwargs.get(m.group(1), '1'),
# The '1' here catches the API version. Slightly hilarious.
base_url + fn['url'] base_url + fn['url']
) )
# Then open and load that shiiit, yo. TODO: check HTTP method and junk, handle errors/authentication # Then open and load that shiiit, yo. TODO: check HTTP method and junk, handle errors/authentication
if fn['method'] == 'POST': if fn['method'] == 'POST':
resp, content = self.client.request(base, fn['method'], urllib.urlencode(dict([k, Twython.encode(v)] for k, v in kwargs.items())), headers = self.headers) resp, content = self.client.request(base, fn['method'], urllib.urlencode(
dict([k, Twython.encode(v)] for k, v in kwargs.items())), headers=self.headers)
else: else:
url = base + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in kwargs.iteritems()]) url = base + "?" + "&".join(["%s=%s" % (key, value) for (key, value) in kwargs.iteritems()])
resp, content = self.client.request(url, fn['method'], headers = self.headers) resp, content = self.client.request(url, fn['method'], headers=self.headers)
return simplejson.loads(content) return simplejson.loads(content)
@ -211,26 +219,28 @@ class Twython(object):
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 AuthError("Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s" % (
resp['status'], content))
try: try:
request_tokens = dict(urlparse.parse_qsl(content)) request_tokens = dict(urlparse.parse_qsl(content))
except: except:
request_tokens = dict(cgi.parse_qsl(content)) request_tokens = dict(cgi.parse_qsl(content))
oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed')=='true' oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed') == 'true'
if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob' and oauth_callback_confirmed: if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob' and oauth_callback_confirmed:
import warnings import warnings
warnings.warn("oauth2 library doesn't support OAuth 1.0a type callback, but remote requires it") warnings.warn("oauth2 library doesn't support OAuth 1.0a type callback, but remote requires it")
oauth_callback_confirmed = False 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 # Use old-style callback argument
if OAUTH_CALLBACK_IN_URL or (callback_url!='oob' and not oauth_callback_confirmed): if OAUTH_CALLBACK_IN_URL or (callback_url != 'oob' and not oauth_callback_confirmed):
auth_url_params['oauth_callback'] = callback_url 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)
@ -257,10 +267,12 @@ class Twython(object):
@staticmethod @staticmethod
def constructApiURL(base_url, params): def constructApiURL(base_url, params):
return base_url + "?" + "&".join(["%s=%s" %(Twython.unicode2utf8(key), urllib.quote_plus(Twython.unicode2utf8(value))) for (key, value) in params.iteritems()]) return base_url + "?" + "&".join(
["%s=%s" % (Twython.unicode2utf8(key), urllib.quote_plus(Twython.unicode2utf8(value))) for (key, value) in
params.iteritems()])
@staticmethod @staticmethod
def shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"): def shortenURL(url_to_shorten, shortener="http://is.gd/api.php", query="longurl"):
"""shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl") """shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl")
Shortens url specified by url_to_shorten. Shortens url specified by url_to_shorten.
@ -270,12 +282,13 @@ class Twython(object):
shortener - In case you want to use a url shortening service other than is.gd. shortener - In case you want to use a url shortening service other than is.gd.
""" """
try: try:
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)
A method to do bulk user lookups against the Twitter API. Arguments (ids (numbers) / screen_names (strings)) should be flat Arrays that A method to do bulk user lookups against the Twitter API. Arguments (ids (numbers) / screen_names (strings)) should be flat Arrays that
@ -290,7 +303,7 @@ class Twython(object):
lookupURL = Twython.constructApiURL("http://api.twitter.com/%d/users/lookup.json" % version, kwargs) lookupURL = Twython.constructApiURL("http://api.twitter.com/%d/users/lookup.json" % version, kwargs)
try: try:
resp, content = self.client.request(lookupURL, "POST", headers = self.headers) resp, content = self.client.request(lookupURL, "POST", headers=self.headers)
return simplejson.loads(content) return simplejson.loads(content)
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)
@ -307,7 +320,7 @@ class Twython(object):
""" """
searchURL = Twython.constructApiURL("http://search.twitter.com/search.json", kwargs) searchURL = Twython.constructApiURL("http://search.twitter.com/search.json", kwargs)
try: try:
resp, content = self.client.request(searchURL, "GET", headers = self.headers) resp, content = self.client.request(searchURL, "GET", headers=self.headers)
return simplejson.loads(content) return simplejson.loads(content)
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)
@ -322,9 +335,10 @@ class Twython(object):
e.g x.searchTwitter(q="jjndf", page="2") e.g x.searchTwitter(q="jjndf", page="2")
""" """
searchURL = Twython.constructApiURL("http://search.twitter.com/search.json?q=%s" % Twython.unicode2utf8(search_query), kwargs) searchURL = Twython.constructApiURL(
"http://search.twitter.com/search.json?q=%s" % Twython.unicode2utf8(search_query), kwargs)
try: try:
resp, content = self.client.request(searchURL, "GET", headers = self.headers) resp, content = self.client.request(searchURL, "GET", headers=self.headers)
data = simplejson.loads(content) data = simplejson.loads(content)
except HTTPError, e: except HTTPError, e:
raise TwythonError("searchTwitterGen() failed with a %s error code." % `e.code`, e.code) raise TwythonError("searchTwitterGen() failed with a %s error code." % `e.code`, e.code)
@ -343,7 +357,7 @@ class Twython(object):
for tweet in self.searchTwitterGen(search_query, **kwargs): for tweet in self.searchTwitterGen(search_query, **kwargs):
yield tweet yield tweet
def isListMember(self, list_id, id, username, version = 1): def isListMember(self, list_id, id, username, version=1):
""" isListMember(self, list_id, id, version) """ isListMember(self, list_id, id, version)
Check if a specified user (id) is a member of the list in question (list_id). Check if a specified user (id) is a member of the list in question (list_id).
@ -357,12 +371,14 @@ 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) return simplejson.loads(content)
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)
def isListSubscriber(self, username, list_id, id, version = 1): def isListSubscriber(self, username, list_id, id, version=1):
""" isListSubscriber(self, list_id, id, version) """ isListSubscriber(self, list_id, id, version)
Check if a specified user (id) is a subscriber of the list in question (list_id). Check if a specified user (id) is a subscriber of the list in question (list_id).
@ -376,13 +392,15 @@ 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) return simplejson.loads(content)
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)
# The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set. # The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set.
def updateProfileBackgroundImage(self, filename, tile="true", version = 1): def updateProfileBackgroundImage(self, filename, tile="true", version=1):
""" updateProfileBackgroundImage(filename, tile="true") """ updateProfileBackgroundImage(filename, tile="true")
Updates the authenticating user's profile background image. Updates the authenticating user's profile background image.
@ -398,12 +416,14 @@ class Twython(object):
fields = [] fields = []
content_type, body = Twython.encode_multipart_formdata(fields, files) content_type, body = Twython.encode_multipart_formdata(fields, files)
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
r = urllib2.Request("http://api.twitter.com/%d/account/update_profile_background_image.json?tile=%s" % (version, tile), body, headers) r = urllib2.Request(
"http://api.twitter.com/%d/account/update_profile_background_image.json?tile=%s" % (version, tile), body
, headers)
return urllib2.urlopen(r).read() return urllib2.urlopen(r).read()
except HTTPError, e: except HTTPError, e:
raise TwythonError("updateProfileBackgroundImage() failed with a %d error code." % e.code, e.code) raise TwythonError("updateProfileBackgroundImage() failed with a %d error code." % e.code, e.code)
def updateProfileImage(self, filename, version = 1): def updateProfileImage(self, filename, version=1):
""" updateProfileImage(filename) """ updateProfileImage(filename)
Updates the authenticating user's profile image (avatar). Updates the authenticating user's profile image (avatar).
@ -434,19 +454,36 @@ class Twython(object):
""" """
url = "http://api.twitter.com/%s/users/profile_image/%s.json" % (version, username) url = "http://api.twitter.com/%s/users/profile_image/%s.json" % (version, username)
if size: if size:
url = self.constructApiURL(url, {'size':size}) url = self.constructApiURL(url, {'size': size})
client = httplib2.Http() client = httplib2.Http()
client.follow_redirects = False client.follow_redirects = False
resp, content = client.request(url, 'GET') resp, content = client.request(url, 'GET')
if resp.status in (301,302,303,307): if resp.status in (301, 302, 303, 307):
return resp['location'] return resp['location']
elif resp.status == 200: elif resp.status == 200:
return simplejson.loads(content) return simplejson.loads(content)
raise TwythonError("getProfileImageUrl() failed with a %d error code." % resp.status, resp.status) raise TwythonError("getProfileImageUrl() failed with a %d error code." % resp.status, resp.status)
def getUserProfile(self, **kwargs):
"""getUserProfile(screen_name, **kwargs)
Returns user profile that match a specified screen_name.
Parameters:
See the documentation at https://dev.twitter.com/docs/api/1/get/users/show. Pass in the API supported arguments as named parameters.
e.g x.searchTwitter(screen_name="lacion"[, user_id=123[, include_entities=True]])
"""
userShowURL = Twython.constructApiURL("http://api.twitter.com/version/users/show.json", kwargs)
try:
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
return simplejson.loads(content)
except HTTPError, e:
raise TwythonError("getUserProfile() failed with a %s error code." % `e.code`, e.code)
@staticmethod @staticmethod
def encode_multipart_formdata(fields, files): def encode_multipart_formdata(fields, files):
BOUNDARY = mimetools.choose_boundary() BOUNDARY = mimetools.choose_boundary()
@ -480,6 +517,6 @@ class Twython(object):
@staticmethod @staticmethod
def encode(text): def encode(text):
if isinstance(text, (str,unicode)): if isinstance(text, (str, unicode)):
return Twython.unicode2utf8(text) return Twython.unicode2utf8(text)
return str(text) return str(text)