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