+++ /dev/null
-""" Introduction
-
-This series of tutorials is designed to introduce you to key
-concepts of Tweepy. By the end of this series you should be ready
-to create your grand Twitter application with Tweepy!
-
-If you get lost on your journey to becoming a Tweepy guru, feel
-free to post questions to tweepy@googlegroups.com
-
-Each tutorial file is named tX.py where X is the tutorial number.
-Work your way from 1 and up. These files should be runnable by python.
-Be sure the tweepy library is on your python path by either installing
-it on your system OR setting the PYTHONPATH environment variable.
-You can then run the tutorial like such:
-
- python t1.py
-
-Tutorials:
-
- 1 -- Authentication
- 2 -- API
- 3 -- Models
- 4 -- Errors
- 5 -- Cache
- 6 -- Pagination
-
-Author: Joshua Roesslein
-"""
-
+++ /dev/null
-from getpass import getpass
-import cPickle as pickle
-import tweepy
-
-""" Tutorial 1 -- Authentication
-
-Tweepy supports both basic auth and OAuth authentication. It is
-recommended you use OAuth so you can be more secure and also
-set a custom "from xxx" for you application.
-
-Authentication is handled by AuthHandler instances. You must either
-create a BasicAuthHandler or OAuthHandler which we will pass into our
-api instance to let twitter know who we are.
-
-First let's try creating a basic auth handler.
-"""
-username = raw_input('Twitter username: ')
-password = getpass('Twitter password: ')
-basic_auth = tweepy.BasicAuthHandler(username, password)
-
-"""
-Now for an OAuth handler...
-
-You must supply the handler both your consumer key and secret which
-twitter supplies you with at http://twitter.com/oauth_clients
-You may also supply a callback URL as an optional parameter.
-"""
-consumer_key = 'ZbzSsdQj7t68VYlqIFvdcA'
-consumer_secret = '4yDWgrBiRs2WIx3bfvF9UWCRmtQ2YKpKJKBahtZcU'
-oauth_auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
-oauth_auth_callback = tweepy.OAuthHandler(consumer_key, consumer_secret,
- 'http://test.com/my/callback/url')
-
-"""
-We must redirect the user to twitter so they can authorize us.
-To do this you will ask the OAuthHandler for the authorization URL
-which you will then display to the user OR open their browser to that URL.
-For this example we will just print the URL to the console.
-"""
-print 'Please authorize us: %s' % oauth_auth.get_authorization_url()
-
-"""
-Now that we have been authorized, we must fetch the access token.
-To do this the user must either supply us with a PIN OR if we are using a callback
-we must wait for that and grab the verifier number from the request.
-For this example we will ask the user for the PIN.
-"""
-verifier = raw_input('PIN: ').strip()
-oauth_auth.get_access_token(verifier)
-
-"""
-Okay we are all set then with OAuth. If you want to store the access
-token for later use, here's how...
-"""
-access_token = oauth_auth.access_token
-print 'Access token: %s' % access_token
-
-"""
-For later use we will keep the token pickled into a file.
-"""
-token_file = open('oauth_token', 'wb')
-pickle.dump(access_token, token_file)
-token_file.close()
-
-"""
-And to reload the token...
-"""
-token_file = open('oauth_token', 'rb')
-oauth_token = pickle.load(token_file)
-token_file.close()
-oauth_auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
-oauth_auth.access_token = access_token
-
-"""
-Now let's plugin our newly created auth handler into an API instance
-so we can start playing with the Twitter API. :)
-"""
-api_via_basic = tweepy.API(basic_auth)
-api_via_oath = tweepy.API(oauth_auth)
-
-""" API.new() shortcut
-
-To make creating API instances a bit more easy you way use the
-static method API.new() to create new instances. Here is an example:
-"""
-new_basic_api = tweepy.API.new('basic', username, password)
-new_oauth_api = tweepy.API.new('oauth', consumer_key, consumer_secret)
-new_oauth_api.auth_handler # here's how to access the auth handler to do the oauth flow
-
-""" The End
-
-That wraps up this first tutorial. You have learned how to setup
-authentication and create an API instance which can then be used
-to interact with the Twitter API.
-
-We are now ready for Tutorial 2.
-"""
-
+++ /dev/null
-import tweepy
-from t1 import oauth_auth
-
-""" Tutorial 2 -- API
-
-This tutorial will focus on creating and using the API class.
-The API class is the primary interface between your application
-and Twitter's API. It implements most of the endpoint documented here:
- http://apiwiki.twitter.com/Twitter-API-Documentation
-"""
-
-"""
-The API class can be used in either authenticated or non-authenticated modes.
-First let's demonstrate using the API class without authentication...
-"""
-no_auth_api = tweepy.API()
-
-"""
-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
-
-"""
-Tweepy provides a non-authenticated instance of the API for you already
-so you don't normally need to create one your self.
-"""
-tweepy.api # non-auth instance of API
-
-"""
-Any endpoint that does not require authentication can be accessed
-with this non-authenticated API instance. If you try to access an
-API endpoint that does require authentication, a TweepError exception
-will be raised.
-"""
-
-"""
-Now we will create an authenticated instance of the API class
-using the auth handler we created in tutorial 1.
-"""
-auth_api = tweepy.API(oauth_auth)
-
-"""
-Let's query the authenticated user's friends timeline
-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
-
-""" The End
-
-So that wraps up this tutorial. You now know how to create both
-non-authenticated and authenticated instances of the API class.
-
-Onto the next tutorial!
-"""
-
+++ /dev/null
-import tweepy
-
-""" Tutorial 3 -- Models
-
-Tweepy uses a set of models to transfer data from the
-Twitter API to your python application. The following
-models are used...
-
- Status, User, DirectMessage, Friendship,
- SavedSearch, SearchResult
-"""
-
-""" Custom Models
-A nice feature of Tweepy is that you can extend or even provide
-your own implementations of these models. Tweepy simply just sets
-the attributes and returns back an instance of your model class.
-This makes it easy to integrate your ORM into Tweepy.
-"""
-
-"""
-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)
-
-"""
-We must now register our implementation of Status with tweepy.
-"""
-tweepy.models['status'] = MyStatus
-
-"""
-Now to test out our new status model...
-"""
-s = tweepy.api.get_status(123)
-print 'Length of status 123: %i' % s.length()
-
-"""
-As you can see once you register your model with tweepy
-it will be used for each API call. If you want to restore
-the Status model to tweepy's implementation...
-"""
-tweepy.models['status'] = tweepy.Status
-
-""" Validation
-
-Tweepy's models include a method validate() which can check to
-make sure no data is missing from the model. By default the API class
-will call this method before returning the models. If the model is
-invalid a TweepError exception will be raised. Validation is handy
-to make sure data is present which your application depends on.
-Here's a demo...
-"""
-try:
- 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
-
-"""
-To disable auto validation...
-"""
-tweepy.api.validate = False
-
-""" Shortcuts
-
-Some of the models include shortcut functions for accessing
-related data from the API.
-In this next demo I will show you how to get a list of an user's
-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
-
-"""
-To learn about all shortcuts check out the reference documentation.
-"""
-
-""" _api attribute
-
-Shortcuts are possible due to the _api attribute. This is a
-reference to the API instance that created the model. Normally you
-can just ignore this, but if you plan to pickle or store your models
-you must not store this reference. It will not be valid from one
-python instance to the next. When you restore your model from storage
-you must re-link it to an API instance if you plan to use the shortcuts.
-Example:
-
-u = get_from_storage()
-u._api = my_api_instance
-
-"""
-
-""" The End
-
-This concludes the tutorial on models. You have learned how to
-implement your own models, perform validation, and using shortcuts
-to access related data.
-"""
-
+++ /dev/null
-import tweepy
-
-""" Tutorial 4 -- Errors
-
-Errors are going to happen sooner or later in your applications.
-This tutorial will show you how to properly catch these errors in
-Tweepy and handle them gracefully in your application.
-"""
-
-""" TweepError
-
-Tweepy uses a single exception: tweepy.TweepError.
-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!')
-except tweepy.TweepError, e:
- print 'Failed to update! %s' % e
-
-"""
-TweepError's can be casted to string format which will
-give details as to what went wrong.
-The main reasons an exception will be raised include:
-
- -HTTP request to twitter failed
- -Model failed validation
- -Trying to use an authenticated API endpoint w/o authenticating
- -Invalid parameters supplied to API methods
- -Authentication failures
-
-Be sure to keep a look out for these exceptions and handle them properly.
-"""
-
-"""
-If Twitter returns an error response you may wish to retry the request
-again. To help make this easier Tweepy allows you to configure it to do
-this for you automatically when such error codes are returned.
-
-Here is an example of performing a request and retrying if it fails.
-We will tell Tweepy to only attempt up to 5 retries and wait 5 seconds
-between each attempt.
-"""
-try:
- tweepy.api.friends_timeline(retry_count=5, retry_delay=5)
-except tweepy.TweepError, e:
- # If all 5 attempts fail a TweepError will be thrown
- print 'Failed to get timeline: %s' % e
-
-"""
-By default Tweepy will retry on any non-200 status code returned by twitter.
-The default retry_delay is zero, so if no delay is provided Tweepy will retry right away.
-
-Let's say we want to retry on status code responses of 400 only.
-Here is how we do that...
-"""
-try:
- tweepy.api.user_timeline('twitter', retry_count=3, retry_delay=5, retry_errors=[400])
-except tweepy.TweepError, e:
- print 'Failed to get timeline: %s' % e
-
-""" The End """
-
+++ /dev/null
-import tweepy
-
-""" Tutorial 5 -- Cache
-
-Tweepy provides a caching layer for frequently
-requested data. This can help cut down on Twitter API
-requests helping to make your application faster.
-By default caching is disabled in API instances.
-"""
-
-"""
-Let's create a new API instance with caching enabled.
-Tweepy comes with both a memory and file based cache.
-In this example we will be using the memory cache.
-"""
-cached_api = tweepy.API(cache=tweepy.MemoryCache(timeout=120))
-
-"""
-Now we can use this API instance and any request that uses
-'GET' will be cached for 120 seconds. If no timeout is specified
-the default is 60 seconds.
-Here is a demo using our new cached API instance...
-"""
-non_cached_result = cached_api.public_timeline()
-cached_result = cached_api.public_timeline()
-
-"""
-The first request (non_cached_result) will require a trip
-to the Twitter server. The second request (cached_result)
-will be retrieved from the cache saving a trip to Twitter.
-"""
-
-""" Your own cache implementation
-
-If you wish to use your own cache implementation just
-extend the Cache interface class (tweepy/cache.py).
-Then when you create your API instance pass it in.
-"""
-#my_api = tweepy.API(cache=MyCache())
-
-""" The End """
-
+++ /dev/null
-import tweepy
-
-api = tweepy.API.new(username='', password='')
-
-""" Tutorial 6 -- Pagination
-
-Pagination is used in the API for iterating through
-lists of users, statuses, etc. Each segment of items
-is called a "page". In the twitter API you control which page
-you are currently on with the "page" parameter. To move forward
-just increment the parameter. To move backward you just decrement it.
-"""
-
-"""
-First let's do a simple loop iterating through the first
-30 statuses in our "friends" timeline. We will first
-do this without the Cursor helper object which we will
-demonstrate later on.
-"""
-print 'Pagination without Cursor...'
-count = 0
-current_page = 1
-running = True
-while running:
-
- page = api.friends_timeline(page=current_page)
- if len(page) == 0:
- # No more data, stop
- break
- for status in page[:30]:
- if count == 30:
- # We only want 30 statuses
- running = False
- break
- count += 1
- print status.text
- current_page += 1
-
-print ''
-
-"""
-While the above works correctly, it does
-require that we manage the pagination
-manually. This is not a really pretty way to paginate.
-Now we will perform the same action, but
-using the Cursor object.
-"""
-print 'Pagination with cursor...'
-cursor = tweepy.Cursor(api.friends_timeline)
-for status in cursor.items(limit=30):
-
- print status.text
-
-print ''
-
-"""
-As you can see this is much simpler and all the
-pagination is managed for us automatically.
-We pass into the Cursor constructor the API method
-we wish to paginate. Cursor then has two methods that returns
-an iterator:
- Cursor.items() -- iterate item by item until limit is reached
- Cursor.pages() -- iterate page by page until limit is reached
-
-If limit is not specified iteration will continue until twitter
-stops sending us pages (pagination limit reached or no more data).
-The limit for items() is the maximum number of items to iterate.
-For pages() limit is the maximum number of pages to iterate.
-The page size varies for each API method, so read the wiki page
-for more details.
-
-Using Cursor also works for both "cursor" and "page" based pagination.
-This means you get a standard interface to both methods of pagination
-in your code. So if twitter changes future methods to "cursor" based
-you only need to update Tweepy.
-"""
-
-"""
-Let's do one more example, this time iterating by "pages".
-"""
-print 'Pagination of friends ids page by page...'
-cursor = tweepy.Cursor(api.friends_ids)
-for page in cursor.pages():
-
- print page
-
-print ''
-
-# TODO: demo next() and prev()