Testing the twitter app on local server in django

2019-04-15 13:33发布

问题:

I am using the twython library, to do handshakes with twitter python library. And I am testing things on my local server, 127.0.0.1:8000

This is my first django view, that generates the twitter tokens for users.

def twitter_auth(request):
    """
        The view function that initiates the entire handshake.
        For the most part, this is 100% drag and drop.
    """
    # Instantiate Twython with the first leg of our trip.
    twitter = Twython(
            settings.TWITTER_KEY,
            settings.TWITTER_SECRET,
            )
        # Then send them over there, durh.
        tw_callback_url = request.build_absolute_uri(reverse('social_home'))
    twitter_auth = twitter.get_authentication_tokens(callback_url=tw_callback_url)
        request.session['twitter_auth'] = twitter_auth
    return HttpResponseRedirect(twitter_auth['auth_url'])

From the above view, the user is redirected to the second view, where I wish to read the timeline of the user, I do it in following manner -

def social_home(request):
    oauth_token_secret = request.session['twitter_auth']['oauth_token_secret']
    oauth_token = request.session['twitter_auth']['oauth_token']
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret)
    authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier'])
    user_tweets = twitter.get_home_timeline()
    return render(request, "social_summary.html", {"user_tweets":user_tweets})

But here, I get the following error - Twitter API returned a 401 (Unauthorized), Invalid or expired token

Please help me know, where I am wrong.

Thanks for your time.

回答1:

def social_home(request):
    oauth_token_secret = request.session['twitter_auth']['oauth_token_secret']
    oauth_token = request.session['twitter_auth']['oauth_token']
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret)
    authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier'])

    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, authorized_tokens['oauth_token'], authorized_tokens['oauth_token_secret'])
    user_tweets = twitter.get_home_timeline()
    return render(request, "social_summary.html", {"user_tweets":user_tweets})

That should work! :) Good luck!