Webapp callback -- "TweepError: 'OAuthHandler' object has no attribute 'request_token'"

oauth
rest
python

#1

I am trying to get a mechanism to send tweets on behalf of a user working for a web app. I have been trying a couple different ways to do this to no avail. Below is my current attempt:

@app.route('/initialAuth')
def do_send_tweet():

    consumer_key = ''
    consumer_secret = ''
    #authenticating twitter consumer key
    auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
    auth.secure=True
    authUrl = auth.get_authorization_url()
    return redirect(authUrl)

def get_access_token(verifier, auth):
    token = auth.get_access_token(verifier=verifier)
    accessTokenFile = open("accessTokens","w")
    return token

def tweet(status, token, auth):
    access_token_key, access_token_secret = token
    print('access_token_key'+access_token_key)
    print('access_token_secret'+access_token_secret)
    if len(status) > 140:
        raise Exception('status message is too long!')
    api = tweepy.API(auth)
    result = api.update_status(status)
    return result

@app.route('/callback')
def do_send_tweet_callback():

    consumer_key = ''
    consumer_secret = ''
    auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
    auth.secure=True

    oauth_verifier = request.args.get("oauth_verifier", "").strip()
    print('oauth_verifier '+str(oauth_verifier))

    token = auth.get_access_token(verifier=oauth_verifier)
    tweet('test tweet', token, auth)
    return 'done'

will result in “TweepError: ‘OAuthHandler’ object has no attribute ‘request_token’” after returning to the callback URL

If I do it as a standalone app(based on http://kinocksebastian.blogspot.ca/2015/04/how-to-get-access-token-using-tweepy-in.html) it will work.

What am I missing here? I am guessing that something is not being transferred in the oauth session accross the callback?


#2

You need to save the request_token from the first step.

authUrl = auth.get_authorization_url()
session.set('request_token', auth.request_token)

and set it on the auth object before getting an access_token.

token = session.get('request_token')
session.delete('request_token')
auth.request_token = token
token = auth.get_access_token(verifier=oauth_verifier)

See the tweepy docs for the full example.