I just wrapped tweepy, but it's a hassle to catch old code and remember how to use it every time, so my Twitter API library and notes on how to use it.
Set the following values in the environment variables.
--TWITTER_CONSUMER_KEY
: "Consumer Key (API Key)" in the "Keys and Access Tokens" tab of the Twitter App
--TWITTER_CONSUMER_SECRET
: "Consumer Secret (API Secret)" in the "Keys and Access Tokens" tab of the Twitter App
--TWITTER_CALLBACK_URL
: "Callback URL" set in the "Settings" tab of the Twitter App
twitter.py
# -*- coding: utf-8 -*-
import os
import urllib2
import os.path
import logging
import traceback
import oauthlib
import tweepy
CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY')
CONSUMER_SECRET = os.environ.get('TWITTER_CONSUMER_SECRET')
CALLBACK_URL = os.environ.get('TWITTER_CALLBACK_URL')
#
def api(access_token = None, access_token_secret = None, with_callback_url = False):
if with_callback_url:
auth = tweepy.OAuthHandler(
consumer_key = CONSUMER_KEY,
consumer_secret = CONSUMER_SECRET,
callback_url = CALLBACK_URL)
else:
auth = tweepy.OAuthHandler(
consumer_key = CONSUMER_KEY,
consumer_secret = CONSUMER_SECRET)
if access_token is not None and access_token_secret is not None:
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
# API
def get_tweets(screen_name = None, hashtag = None, count = 200):
if screen_name is not None:
cursor = tweepy.Cursor(api().user_timeline,
screen_name = screen_name, count = 200, exclude_replies = True)
elif hashtag is not None:
cursor = tweepy.Cursor(api().search, q = u"#{0}".format(hashtag), count = 200)
if count is not None:
return cursor.items(count)
else:
return cursor.items()
def tweet_link(tweet):
return "https://twitter.com/{screen_name}/status/{tweet_id}".format(
screen_name = tweet.user.screen_name,
tweet_id = tweet.id_str)
def get_friends(screen_name):
return tweepy.Cursor(api().friends, screen_name = screen_name, count = 200).items()
# OAuth
def generate_auth_url():
oauth_handler = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL)
redirect_url = oauth_handler.get_authorization_url(signin_with_twitter = True)
request_token = oauth_handler.request_token
return redirect_url, request_token['oauth_token'], request_token['oauth_token_secret'],
def get_access_token(request_token_key, request_token_secret, oauth_verifier):
oauth_handler = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
oauth_handler.request_token = {
'oauth_token': request_token_key,
'oauth_token_secret': request_token_secret,
'oauth_callback_confirmed': True,
}
oauth_handler.get_access_token(oauth_verifier)
return oauth_handler.access_token, oauth_handler.access_token_secret
def verify_credentials(access_token, access_token_secret):
api = api(access_token, access_token_secret)
return api.verify_credentials()
# Utility
def get_big_profile_image_url(profile_image_url):
return profile_image_url.replace('_normal', '')
The code I'm writing is a sample code for Bottle.
@get('/twitter_login')
def twitter_login():
auth_url, request_token_key, request_token_secret = twitter.generate_auth_url()
# request_token_key and request_token_Save the secret in the session.
redirect(auth_url)
Call twitter.generate_auth_url
to issue the URL, request token, and secret to be sent to Twitter.
Then, the request token and secret are saved in the session. The value saved here is used when acquiring the access token in the callback process from Twitter.
I think that the implementation is different depending on the person here, but I store the request token and secret in the database and put only the request token in the cookie. Also, as a CSFR measure, * access source IP * or * User Agent * may also be included in the database.
Then redirect to Twitter.
@get('/twitter_callback')
def twitter_callback():
#Request token stored in session (request_token_key), secret (request)_token_get secret).
oauth_verifier = request.query['oauth_verifier']
access_token_key, access_token_secret = twitter.get_access_token(
twitter_connect.request_token_key,
twitter_connect.request_token_secret,
oauth_verifier)
twitter_user = twitter.verify_credentials(access_token_key, access_token_secret)
#Processing such as user registration and login
The callback from Twitter contains ʻoauth_verifier`, so use this and the request token and secret that you put in the session to get the access token and secret.
Recommended Posts