removed XML files from pycharm, and fixed indentation chaos i created

back to original indentation
This commit is contained in:
Luis Morales 2011-08-30 20:37:13 +02:00
parent 1a8230bd3e
commit b4da474671
7 changed files with 438 additions and 490 deletions

1
.gitignore vendored
View file

@ -3,3 +3,4 @@ build
dist
twython.egg-info
*.swp
.idea

5
.idea/encodings.xml generated
View file

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

8
.idea/misc.xml generated
View file

@ -1,8 +0,0 @@
<?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
View file

@ -1,9 +0,0 @@
<?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
View file

@ -1,9 +0,0 @@
<?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
View file

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

View file

@ -46,8 +46,7 @@ except ImportError:
from django.utils import simplejson
except:
# 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
@ -73,7 +72,6 @@ class TwythonError(AttributeError):
from twython import TwythonError, APILimit, AuthError
"""
def __init__(self, msg, error_code=None):
self.msg = msg
if error_code == 400:
@ -89,7 +87,6 @@ class APILimit(TwythonError):
docs if you're running into issues here, Twython does not concern itself with
this matter beyond telling you that you've done goofed.
"""
def __init__(self, msg):
self.msg = msg
@ -102,7 +99,6 @@ class AuthError(TwythonError):
Raised when you try to access a protected resource and it fails due to some issue with
your authentication.
"""
def __init__(self, msg):
self.msg = msg
@ -111,8 +107,7 @@ class AuthError(TwythonError):
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)
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
@ -178,24 +173,21 @@ class Twython(object):
I'll hate myself for saying this, but this is heavily inspired by Ruby's "method_missing".
"""
def get(self, **kwargs):
# Go through and replace any mustaches that are in our API url.
fn = api_table[api_call]
base = re.sub(
'\{\{(?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']
)
# Then open and load that shiiit, yo. TODO: check HTTP method and junk, handle errors/authentication
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:
url = base + "?" + "&".join(["%s=%s" % (key, value) for (key, value) in kwargs.iteritems()])
resp, content = self.client.request(url, fn['method'], headers=self.headers)
url = base + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in kwargs.iteritems()])
resp, content = self.client.request(url, fn['method'], headers = self.headers)
return simplejson.loads(content)
@ -219,28 +211,26 @@ class Twython(object):
resp, content = self.client.request(self.request_token_url, "GET", **request_args)
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:
request_tokens = dict(urlparse.parse_qsl(content))
except:
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:
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 = {
'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):
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)
@ -267,12 +257,10 @@ class Twython(object):
@staticmethod
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
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")
Shortens url specified by url_to_shorten.
@ -282,13 +270,12 @@ class Twython(object):
shortener - In case you want to use a url shortening service other than is.gd.
"""
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
except HTTPError, e:
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)
A method to do bulk user lookups against the Twitter API. Arguments (ids (numbers) / screen_names (strings)) should be flat Arrays that
@ -303,7 +290,7 @@ class Twython(object):
lookupURL = Twython.constructApiURL("http://api.twitter.com/%d/users/lookup.json" % version, kwargs)
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)
except HTTPError, e:
raise TwythonError("bulkUserLookup() failed with a %s error code." % `e.code`, e.code)
@ -320,7 +307,7 @@ class Twython(object):
"""
searchURL = Twython.constructApiURL("http://search.twitter.com/search.json", kwargs)
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)
except HTTPError, e:
raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code)
@ -335,10 +322,9 @@ class Twython(object):
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:
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
resp, content = self.client.request(searchURL, "GET", headers = self.headers)
data = simplejson.loads(content)
except HTTPError, e:
raise TwythonError("searchTwitterGen() failed with a %s error code." % `e.code`, e.code)
@ -357,7 +343,7 @@ class Twython(object):
for tweet in self.searchTwitterGen(search_query, **kwargs):
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)
Check if a specified user (id) is a member of the list in question (list_id).
@ -371,14 +357,12 @@ 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.
"""
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)
except HTTPError, e:
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)
Check if a specified user (id) is a subscriber of the list in question (list_id).
@ -392,15 +376,13 @@ 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.
"""
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)
except HTTPError, e:
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.
def updateProfileBackgroundImage(self, filename, tile="true", version=1):
def updateProfileBackgroundImage(self, filename, tile="true", version = 1):
""" updateProfileBackgroundImage(filename, tile="true")
Updates the authenticating user's profile background image.
@ -416,14 +398,12 @@ class Twython(object):
fields = []
content_type, body = Twython.encode_multipart_formdata(fields, files)
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()
except HTTPError, e:
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)
Updates the authenticating user's profile image (avatar).
@ -454,13 +434,13 @@ class Twython(object):
"""
url = "http://api.twitter.com/%s/users/profile_image/%s.json" % (version, username)
if size:
url = self.constructApiURL(url, {'size': size})
url = self.constructApiURL(url, {'size':size})
client = httplib2.Http()
client.follow_redirects = False
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']
elif resp.status == 200:
return simplejson.loads(content)
@ -468,18 +448,23 @@ class Twython(object):
raise TwythonError("getProfileImageUrl() failed with a %d error code." % resp.status, resp.status)
def getUserProfile(self, **kwargs):
"""getUserProfile(screen_name, **kwargs)
"""getUserProfile(**kwargs)
Parameters:
username - Required. User name of the user you want the profile information.
OR
id - Required. User id of the user you want the profile information.
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]])
e.g x.getUserProfile(screen_name="lacion"[, user_id=123[, include_entities=True]])
"""
userShowURL = Twython.constructApiURL("http://api.twitter.com/version/users/show.json", kwargs)
userShowURL = Twython.constructApiURL("http://api.twitter.com/1/users/show.json", kwargs)
try:
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
resp, content = self.client.request(userShowURL, "GET", headers=self.headers)
return simplejson.loads(content)
except HTTPError, e:
raise TwythonError("getUserProfile() failed with a %s error code." % `e.code`, e.code)
@ -517,6 +502,6 @@ class Twython(object):
@staticmethod
def encode(text):
if isinstance(text, (str, unicode)):
if isinstance(text, (str,unicode)):
return Twython.unicode2utf8(text)
return str(text)