Python & Twitter OAuth

I always need to rethink again whenever I need to deal with Twitter OAuth, which annoys me a lot. Therefore I decided to put it in here as a simple article, so I can easily find the information I need in the future.

Before testing Twitter OAuth, you will need to create your application in here. If you have any question about creating Twitter application, please follow this good article How to register a Twitter APP in 8 easy steps to create the app step by step.

twitter is a very popular Python package, you can use easy_install command to install the package in your environment.

$ easy_install twitter
$ python
>>> import twitter
>>> print(twitter)
<module 'twitter' from '/Library/Python/2.7/site-packages/twitter-1.13.1-py2.7.egg/twitter/__init__.pyc'>

Once you installed twitter package; you will need to find out your Twitter consumer key and consumer secret first. Please go to apps.twitter.com and use Test Oauth to find out the consumer key and consumer secret.

You can find out Test OAuth button on your application page

You can find out Test OAuth button on your application page

On Test OAuth page, you should be able to find your Consumer key and Consumer secret

On Test OAuth page, you should be able to find your Consumer key and Consumer secret

In the real development, you should always keep your keys in a safe place, but this is only for testing, please just simply paste your consumer key and consumer secret into our testing file.

import os
import twitter

CONSUMER_KEY = '{Please get your consumer key from Twitter}'
CONSUMER_SECRET = '{Please get your consumer secret from Twitter}'
TWITTER_CREDENTIALS = os.path.expanduser('./.twitter_credentials')
if not os.path.exists(TWITTER_CREDENTIALS):
    twitter.oauth_dance("SqView", CONSUMER_KEY, CONSUMER_SECRET, TWITTER_CREDENTIALS)

oauth_token, oauth_secret = twitter.read_token_file(TWITTER_CREDENTIALS)

t = twitter.Twitter(auth = twitter.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
result = t.statuses.home_timeline(count=5)
print(result)

This script will use twitter.oauth_dance to get your credential information and save as .twitter_credentials. When you execute this script, it will link to Twitter page and ask you to authorize your APP to use your account. Once you authorized it, you have to paste the pin code back to your script.

$ python testing.py 
Hi there! We're gonna get you all set up to use SqView.

In the web browser window that opens please choose to Allow
access. Copy the PIN number that appears on the next page and paste or
type it here:

Opening: http://api.twitter.com/oauth/authorize?oauth_token=xxxxx

Please enter the PIN:

It will bring you to the authorize page.

Twitter Authorize Page

Twitter Authorize Page

You should be able to see your Twitter timeline result right now.

The best thing about this library is all the methods are basically the same as Twitter API, so you can always refer to the official Twitter API document to get more information. I list some useful methods in here so I don’t need to search everything over and over again.

Get Home Timeline – statuses.home_timeline()

Document: GET statuses/home_timeline

items = t.statuses.home_timeline(count=5)
for index, item in enumerate(items):
    print(item['user']['screen_name'], item['text'])

Result:

$ python testing.py 
(u'liquidagency', u'Register / save the date - May 2-3  - @ASID Design to Lead Summit with @MartyNeumeier keynote http://t.co/JxCdJBWwTs')
(u'mashable', u'One of the most famous Reddit users has revealed his real identity  http://t.co/t37GpYQIFM')
(u'TheOnlyDJQualls', u"A Saudi prince once (allegedly) offered me $10K to hold my penis while I pee. If people don't start watching @legitfxx...I have a mortgage.")
(u'shanghaiist', u'\u9646\u5730\u7a7a\u95f4\u62e5\u6324\uff0c\u4e0a\u6d77\u8d8a\u6765\u8d8a\u591a\u4eba\u9009\u62e9\u6d77\u846c\u3002Burials at sea gain popularity as Shanghai loses space for land burials.\n http://t.co/rpEMFsClPT')
(u'DashBurst', u'Yelp Reviews and Ratings Have Officially Made Their Way to Yahoo Search http://t.co/Ld8Rizg67r')

Post Tweet – statuses.update()

Document: POST statuses/update

t.statuses.update(status="Test Tweet via my #Python script")

Result:

My test tweet

My test tweet

Search Tweets – search.tweets()

Document: GET search/tweets

t.search.tweets(q="#python")

Related Links:

Advertisements

One thought on “Python & Twitter OAuth

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s