Commit a00f378d authored by Josh Roesslein's avatar Josh Roesslein
Browse files

2 space -> 4 space indents

parent 4b126837
...@@ -5,17 +5,18 @@ from getpass import getpass ...@@ -5,17 +5,18 @@ from getpass import getpass
import tweepy import tweepy
class StreamWatcherListener(tweepy.StreamListener): class StreamWatcherListener(tweepy.StreamListener):
def on_status(self, status): def on_status(self, status):
print status.text print status.text
def on_error(self, status_code): def on_error(self, status_code):
print 'An error has occured! Status code = %s' % status_code print 'An error has occured! Status code = %s' % status_code
return True # keep stream alive return True # keep stream alive
def on_timeout(self): def on_timeout(self):
print 'Snoozing Zzzzzz' print 'Snoozing Zzzzzz'
# Prompt for login credentials and setup stream object # Prompt for login credentials and setup stream object
username = raw_input('Twitter username: ') username = raw_input('Twitter username: ')
...@@ -24,38 +25,37 @@ stream = tweepy.Stream(username, password, StreamWatcherListener()) ...@@ -24,38 +25,37 @@ stream = tweepy.Stream(username, password, StreamWatcherListener())
# Prompt for mode of streaming and connect # Prompt for mode of streaming and connect
while True: while True:
mode = raw_input('Mode? [sample/filter] ') mode = raw_input('Mode? [sample/filter] ')
if mode == 'sample': if mode == 'sample':
stream.sample() stream.sample()
break break
elif mode == 'filter': elif mode == 'filter':
follow_list = raw_input('Users to follow (comma separated): ').strip() follow_list = raw_input('Users to follow (comma separated): ').strip()
track_list = raw_input('Keywords to track (comma seperated): ').strip() track_list = raw_input('Keywords to track (comma seperated): ').strip()
if follow_list: if follow_list:
follow_list = [u for u in follow_list.split(',')] follow_list = [u for u in follow_list.split(',')]
else: else:
follow_list = None follow_list = None
if track_list: if track_list:
track_list = [k for k in track_list.split(',')] track_list = [k for k in track_list.split(',')]
else:
track_list = None
stream.filter(follow_list, track_list)
break
else: else:
track_list = None print 'Invalid choice! Try again.'
stream.filter(follow_list, track_list)
break
else:
print 'Invalid choice! Try again.'
# Run in a loop until termination # Run in a loop until termination
while True: while True:
try: try:
if stream.running is False: if stream.running is False:
print 'Stream stopped!' print 'Stream stopped!'
break break
time.sleep(1) time.sleep(1)
except KeyboardInterrupt: except KeyboardInterrupt:
break break
# Shutdown connection # Shutdown connection
stream.disconnect() stream.disconnect()
print 'Bye!' print 'Bye!'
...@@ -5,177 +5,180 @@ ...@@ -5,177 +5,180 @@
import unittest import unittest
import random import random
from time import sleep from time import sleep
import os
from tweepy import * from tweepy import *
"""Configurations""" """Configurations"""
# Must supply twitter account credentials for tests # Must supply twitter account credentials for tests
username = '' username = 'tweebly'
password = '' password = 'josh1987twitter'
"""Unit tests""" """Unit tests"""
# API tests
class TweepyAPITests(unittest.TestCase): class TweepyAPITests(unittest.TestCase):
def setUp(self): def setUp(self):
self.api = API(BasicAuthHandler(username, password)) self.api = API(BasicAuthHandler(username, password))
def testpublictimeline(self): def testpublictimeline(self):
self.assertEqual(len(self.api.public_timeline()), 20) self.assertEqual(len(self.api.public_timeline()), 20)
def testfriendstimeline(self): def testfriendstimeline(self):
self.assert_(len(self.api.friends_timeline()) > 0) self.assert_(len(self.api.friends_timeline()) > 0)
def testusertimeline(self): def testusertimeline(self):
s = self.api.user_timeline(screen_name='twitter') s = self.api.user_timeline(screen_name='twitter')
self.assert_(len(s) > 0) self.assert_(len(s) > 0)
self.assertEqual(s[0].author.screen_name, 'twitter') self.assertEqual(s[0].author.screen_name, 'twitter')
def testmentions(self): def testmentions(self):
s = self.api.mentions() s = self.api.mentions()
self.assert_(len(s) > 0) self.assert_(len(s) > 0)
self.assert_(s[0].text.find(username) >= 0) self.assert_(s[0].text.find(username) >= 0)
def testgetstatus(self): def testgetstatus(self):
s = self.api.get_status(id=123) s = self.api.get_status(id=123)
self.assertEqual(s.author.id, 17) self.assertEqual(s.author.id, 17)
def testupdateanddestroystatus(self): def testupdateanddestroystatus(self):
# test update # test update
text = 'testing %i' % random.randint(0,1000) text = 'testing %i' % random.randint(0, 1000)
update = self.api.update_status(status=text) update = self.api.update_status(status=text)
self.assertEqual(update.text, text) self.assertEqual(update.text, text)
# test destroy # test destroy
deleted = self.api.destroy_status(id=update.id) deleted = self.api.destroy_status(id=update.id)
self.assertEqual(deleted.id, update.id) self.assertEqual(deleted.id, update.id)
def testgetuser(self): def testgetuser(self):
u = self.api.get_user(screen_name='twitter') u = self.api.get_user(screen_name='twitter')
self.assertEqual(u.screen_name, 'twitter') self.assertEqual(u.screen_name, 'twitter')
def testme(self): def testme(self):
me = self.api.me() me = self.api.me()
self.assertEqual(me.screen_name, username) self.assertEqual(me.screen_name, username)
def testfriends(self): def testfriends(self):
friends = self.api.friends() friends = self.api.friends()
self.assert_(len(friends) > 0) self.assert_(len(friends) > 0)
def testfollowers(self): def testfollowers(self):
followers = self.api.followers() followers = self.api.followers()
self.assert_(len(followers) > 0) self.assert_(len(followers) > 0)
def testdirectmessages(self): def testdirectmessages(self):
dms = self.api.direct_messages() dms = self.api.direct_messages()
self.assert_(len(dms) > 0) self.assert_(len(dms) > 0)
def testsendanddestroydirectmessage(self): def testsendanddestroydirectmessage(self):
# send # send
sent_dm = self.api.send_direct_message(username, 'test message') sent_dm = self.api.send_direct_message(username, 'test message')
self.assertEqual(sent_dm.text, 'test message') self.assertEqual(sent_dm.text, 'test message')
self.assertEqual(sent_dm.sender.screen_name, username) self.assertEqual(sent_dm.sender.screen_name, username)
self.assertEqual(sent_dm.recipient.screen_name, username) self.assertEqual(sent_dm.recipient.screen_name, username)
# destroy # destroy
destroyed_dm = self.api.destroy_direct_message(sent_dm.id) destroyed_dm = self.api.destroy_direct_message(sent_dm.id)
self.assertEqual(destroyed_dm.text, sent_dm.text) self.assertEqual(destroyed_dm.text, sent_dm.text)
self.assertEqual(destroyed_dm.id, sent_dm.id) self.assertEqual(destroyed_dm.id, sent_dm.id)
self.assertEqual(destroyed_dm.sender.screen_name, username) self.assertEqual(destroyed_dm.sender.screen_name, username)
self.assertEqual(destroyed_dm.recipient.screen_name, username) self.assertEqual(destroyed_dm.recipient.screen_name, username)
def testcreatefriendship(self): def testcreatefriendship(self):
friend = self.api.create_friendship('twitter') friend = self.api.create_friendship('twitter')
self.assertEqual(friend.screen_name, 'twitter') self.assertEqual(friend.screen_name, 'twitter')
self.assertTrue(self.api.exists_friendship(username, 'twitter')) self.assertTrue(self.api.exists_friendship(username, 'twitter'))
def testdestroyfriendship(self): def testdestroyfriendship(self):
enemy = self.api.destroy_friendship('twitter') enemy = self.api.destroy_friendship('twitter')
self.assertEqual(enemy.screen_name, 'twitter') self.assertEqual(enemy.screen_name, 'twitter')
self.assertFalse(self.api.exists_friendship(username, 'twitter')) self.assertFalse(self.api.exists_friendship(username, 'twitter'))
def testshowfriendship(self): def testshowfriendship(self):
source, target = self.api.show_friendship(target_screen_name='twtiter') source, target = self.api.show_friendship(target_screen_name='twtiter')
self.assert_(isinstance(source, Friendship)) self.assert_(isinstance(source, Friendship))
self.assert_(isinstance(target, Friendship)) self.assert_(isinstance(target, Friendship))
# Authentication tests
class TweepyAuthTests(unittest.TestCase): class TweepyAuthTests(unittest.TestCase):
consumer_key = 'ZbzSsdQj7t68VYlqIFvdcA' consumer_key = 'ZbzSsdQj7t68VYlqIFvdcA'
consumer_secret = '4yDWgrBiRs2WIx3bfvF9UWCRmtQ2YKpKJKBahtZcU' consumer_secret = '4yDWgrBiRs2WIx3bfvF9UWCRmtQ2YKpKJKBahtZcU'
def testoauth(self): def testoauth(self):
auth = OAuthHandler(self.consumer_key, self.consumer_secret) auth = OAuthHandler(self.consumer_key, self.consumer_secret)
# test getting access token # test getting access token
auth_url = auth.get_authorization_url() auth_url = auth.get_authorization_url()
self.assert_(auth_url.startswith('http://twitter.com/oauth/authorize?')) self.assert_(auth_url.startswith('http://twitter.com/oauth/authorize?'))
print 'Please authorize: ' + auth_url print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip() verifier = raw_input('PIN: ').strip()
self.assert_(len(verifier) > 0) self.assert_(len(verifier) > 0)
access_token = auth.get_access_token(verifier) access_token = auth.get_access_token(verifier)
self.assert_(access_token is not None) self.assert_(access_token is not None)
# build api object test using oauth # build api object test using oauth
api = API(auth) api = API(auth)
api.update_status('test %i' % random.randint(0,1000)) api.update_status('test %i' % random.randint(0, 1000))
def testbasicauth(self): def testbasicauth(self):
auth = BasicAuthHandler(username, password) auth = BasicAuthHandler(username, password)
# test accessing twitter API # test accessing twitter API
api = API(auth) api = API(auth)
api.update_status('test %i' % random.randint(1,1000)) api.update_status('test %i' % random.randint(1, 1000))
# Cache tests
class TweepyCacheTests(unittest.TestCase): class TweepyCacheTests(unittest.TestCase):
timeout = 2.0 timeout = 2.0
memcache_servers = ['127.0.0.1:11211'] # must be running for test to pass memcache_servers = ['127.0.0.1:11211'] # must be running for test to pass
def _run_tests(self, do_cleanup=True): def _run_tests(self, do_cleanup=True):
# test store and get # test store and get
self.cache.store('testkey', 'testvalue') self.cache.store('testkey', 'testvalue')
self.assertEqual(self.cache.get('testkey'), 'testvalue', 'Stored value does not match retrieved value') self.assertEqual(self.cache.get('testkey'), 'testvalue',
'Stored value does not match retrieved value')
# test timeout
sleep(self.timeout) # test timeout
self.assertEqual(self.cache.get('testkey'), None, 'Cache entry should have expired') sleep(self.timeout)
self.assertEqual(self.cache.get('testkey'), None,
# test cleanup 'Cache entry should have expired')
if do_cleanup:
self.cache.store('testkey', 'testvalue') # test cleanup
sleep(self.timeout) if do_cleanup:
self.cache.cleanup() self.cache.store('testkey', 'testvalue')
self.assertEqual(self.cache.count(), 0, 'Cache cleanup failed') sleep(self.timeout)
self.cache.cleanup()
# test count self.assertEqual(self.cache.count(), 0, 'Cache cleanup failed')
for i in range(0,20):
self.cache.store('testkey%i' % i, 'testvalue') # test count
self.assertEqual(self.cache.count(), 20, 'Count is wrong') for i in range(0, 20):
self.cache.store('testkey%i' % i, 'testvalue')
# test flush self.assertEqual(self.cache.count(), 20, 'Count is wrong')
self.cache.flush()
self.assertEqual(self.cache.count(), 0, 'Cache failed to flush') # test flush
self.cache.flush()
def testmemorycache(self): self.assertEqual(self.cache.count(), 0, 'Cache failed to flush')
self.cache = MemoryCache(timeout=self.timeout)
self._run_tests() def testmemorycache(self):
self.cache = MemoryCache(timeout=self.timeout)
def testfilecache(self): self._run_tests()
os.mkdir('cache_test_dir')
self.cache = FileCache('cache_test_dir', self.timeout) def testfilecache(self):
self._run_tests() os.mkdir('cache_test_dir')
self.cache.flush() self.cache = FileCache('cache_test_dir', self.timeout)
os.rmdir('cache_test_dir') self._run_tests()
self.cache.flush()
def testmemcache(self): os.rmdir('cache_test_dir')
self.cache = MemCache(self.memcache_servers, self.timeout)
self._run_tests(do_cleanup=False) def testmemcache(self):
self.cache = MemCache(self.memcache_servers, self.timeout)
self._run_tests(do_cleanup=False)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main()
unittest.main()
...@@ -21,8 +21,8 @@ Let's query the public timeline and print it to the console... ...@@ -21,8 +21,8 @@ Let's query the public timeline and print it to the console...
public_timeline = no_auth_api.public_timeline() public_timeline = no_auth_api.public_timeline()
print 'Public timeline...' print 'Public timeline...'
for status in public_timeline: for status in public_timeline:
print status.text print status.text
print 'from: %s' % status.author.screen_name print 'from: %s' % status.author.screen_name
""" """
Tweepy provides a non-authenticated instance of the API for you already Tweepy provides a non-authenticated instance of the API for you already
...@@ -50,8 +50,8 @@ and print it to the console... ...@@ -50,8 +50,8 @@ and print it to the console...
friends_timeline = auth_api.friends_timeline() friends_timeline = auth_api.friends_timeline()
print 'Friends timeline...' print 'Friends timeline...'
for status in friends_timeline: for status in friends_timeline:
print status.text print status.text
print 'from: %s' % status.author.screen_name print 'from: %s' % status.author.screen_name
""" The End """ The End
......
...@@ -22,9 +22,9 @@ First let's create our own implementation of Status. ...@@ -22,9 +22,9 @@ First let's create our own implementation of Status.
""" """
class MyStatus(tweepy.Status): class MyStatus(tweepy.Status):
def length(self): def length(self):
"""Return length of status text""" """Return length of status text"""
return len(self.text) return len(self.text)
""" """
We must now register our implementation of Status with tweepy. We must now register our implementation of Status with tweepy.
...@@ -54,10 +54,10 @@ to make sure data is present which your application depends on. ...@@ -54,10 +54,10 @@ to make sure data is present which your application depends on.
Here's a demo... Here's a demo...
""" """
try: try:
u = tweepy.api.get_user('twitter') u = tweepy.api.get_user('twitter')
except TweepError, e: except TweepError, e:
# will be raised if user is invalid OR request failed # will be raised if user is invalid OR request failed
print 'Failed to get user: %s' % e print 'Failed to get user: %s' % e
""" """
To disable auto validation... To disable auto validation...
...@@ -74,7 +74,7 @@ friends by using the User model friends() shortcut... ...@@ -74,7 +74,7 @@ friends by using the User model friends() shortcut...
u = tweepy.api.get_user('twitter') u = tweepy.api.get_user('twitter')
friends = u.friends() friends = u.friends()
for friend in friends: for friend in friends:
print friend.screen_name print friend.screen_name
""" """
To learn about all shortcuts check out the reference documentation. To learn about all shortcuts check out the reference documentation.
......
...@@ -14,9 +14,9 @@ When ever something goes wrong this exception will be raised. ...@@ -14,9 +14,9 @@ When ever something goes wrong this exception will be raised.
Here is an example: Here is an example:
""" """
try: try:
tweepy.api.update_status('this will fail since we are not authenticated!') tweepy.api.update_status('this will fail since we are not authenticated!')
except tweepy.TweepError, e: except tweepy.TweepError, e:
print 'Failed to update! %s' % e print 'Failed to update! %s' % e
""" """
TweepError's can be casted to string format which will TweepError's can be casted to string format which will
......
...@@ -16,3 +16,4 @@ from . streaming import Stream, StreamListener ...@@ -16,3 +16,4 @@ from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API # Global, unauthenticated instance of API
api = API() api = API()
This diff is collapsed.
...@@ -3,86 +3,97 @@ ...@@ -3,86 +3,97 @@
# See LICENSE # See LICENSE
from urllib2 import Request, urlopen from urllib2 import Request, urlopen
from urllib import quote
import base64 import base64
from . import oauth from . import oauth
from . error import TweepError from . error import TweepError
class AuthHandler(object): class AuthHandler(object):
def apply_auth(self, url, method, headers, parameters): def apply_auth(self, url, method, headers, parameters):
"""Apply authentication headers to request""" """Apply authentication headers to request"""
raise NotImplemented raise NotImplemented
class BasicAuthHandler(AuthHandler): class BasicAuthHandler(AuthHandler):
def __init__(self, username, password): def __init__(self, username, password):
self._b64up = base64.b64encode('%s:%s' % (username, password)) self._b64up = base64.b64encode('%s:%s' % (username, password))
def apply_auth(self, url, method, headers, parameters): def apply_auth(self, url, method, headers, parameters):
headers['Authorization'] = 'Basic %s' % self._b64up headers['Authorization'] = 'Basic %s' % self._b64up
"""OAuth authentication handler"""
class OAuthHandler(AuthHandler):
REQUEST_TOKEN_URL = 'http://twitter.com/oauth/request_token' class OAuthHandler(AuthHandler):
AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize' """OAuth authentication handler"""
ACCESS_TOKEN_URL = 'http://twitter.com/oauth/access_token'
REQUEST_TOKEN_URL = 'http://twitter.com/oauth/request_token'
def __init__(self, consumer_key, consumer_secret, callback=None): AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) ACCESS_TOKEN_URL = 'http://twitter.com/oauth/access_token'
self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.request_token = None def __init__(self, consumer_key, consumer_secret, callback=None):
self.access_token = None self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
self.callback = callback self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.request_token = None
def apply_auth(self, url, method, headers, parameters): self.access_token = None
request = oauth.OAuthRequest.from_consumer_and_token(self._consumer, self.callback = callback
http_url=url, http_method=method, token=self.access_token, parameters=parameters)
request.sign_request(self._sigmethod, self._consumer, self.access_token) def apply_auth(self, url, method, headers, parameters):
headers.update(request.to_header()) request = oauth.OAuthRequest.from_consumer_and_token(
self._consumer, http_url=url, http_method=method,
def _get_request_token(self): token=self.access_token, parameters=parameters
try: