Testing the twitter app on local server in django with twython

為{幸葍}努か 提交于 2019-12-12 09:27:53

问题


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!



来源:https://stackoverflow.com/questions/17307105/testing-the-twitter-app-on-local-server-in-django-with-twython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!