【问题标题】:Testing the twitter app on local server in django with twython使用 twython 在 django 的本地服务器上测试 twitter 应用程序
【发布时间】:2013-06-26 05:54:29
【问题描述】:

我正在使用twython library,与 twitter python 库进行握手。 我正在我的本地服务器上测试东西,127.0.0.1:8000

这是我的第一个 django 视图,它为用户生成 twitter 令牌。

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'])

从上面的视图,用户被重定向到第二个视图,我希望读取用户的时间线,我按照以下方式进行 -

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})

但是在这里,我收到以下错误 - Twitter API 返回 401(未授权)、无效或过期的令牌

请帮助我知道我错在哪里。

感谢您的宝贵时间。

【问题讨论】:

  • 您可能需要get_authentication_tokens 代替?
  • 完成,结果相同。 Twitter API returned a 401 (Unauthorized), Failed to validate oauth signature and token
  • 我要做的另一件事是检查 API 密钥和秘密凭据

标签: python django twitter python-twitter twython


【解决方案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})

应该可以! :) 祝你好运!

【讨论】:

  • 感谢它开始工作,但任何想法,为什么你必须添加额外的twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, authorized_tokens['oauth_token'], authorized_tokens['oauth_token_secret']) 另外,我不希望用户每次都授权,因为我需要保存用户特定的, oauth_tokenoauth_token_secret在数据库中,还是我需要保存authorized_tokens??
  • 你需要保存authorized_tokens
  • authorized_tokens 是 OAuth 流程中生成的最终令牌
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 2013-01-17
  • 1970-01-01
  • 2013-08-09
  • 1970-01-01
  • 2015-02-24
相关资源
最近更新 更多