如何使用 Twython 将 oauth_callback 值传递给 oauth/request_token

2024-06-07

Twitter 最近刚刚强制执行以下规定:

1) 您必须通过oauth_callbackoauth/request_token 的值。这不是可选的。即使您已经在 dev.twitter.com 上设置了一个。如果您正在执行带外 OAuth,请通过oauth_callback=oob.

2) 您必须传递oauth_verifier您要么从执行的回调中收到,要么从最终用户手写到 oauth/access_token 中收到。 这是推特主题(https://dev.twitter.com/discussions/16443 https://dev.twitter.com/discussions/16443)

这导致了特威顿get_authorized_tokens抛出这个错误:

Request: oauth/access_token

Error: Required oauth_verifier parameter not provided

我有两个问题:

1.如何通过oauth_callback使用 Twython 来获取 oauth/request_token 的值?

2.如何传递oauth_verifier?

我可以得到oauth_verifier使用回调 URL 中的 request.GET['oauth_verifier'] 但我不知道使用 Twython 从那里做什么。我到处搜索但没有找到任何答案,所以我决定发布此内容。这是我的第一篇文章,所以请友善;)

这是我的代码:

def register_twitter(request):
    # Instantiate Twython with the first leg of our trip.
    twitter = Twython(
        twitter_token = settings.TWITTER_KEY,
        twitter_secret = settings.TWITTER_SECRET,
        callback_url = request.build_absolute_uri(reverse('account.views.twitter_thanks'))
    )

    # Request an authorization url to send the user to
    auth_props = twitter.get_authentication_tokens()

    # Then send them over there
    request.session['request_token'] = auth_props
    return HttpResponseRedirect(auth_props['auth_url'])


def twitter_thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL):

    # Now that we've got the magic tokens back from Twitter, we need to exchange
    # for permanent ones and store them...
    twitter = Twython(
        twitter_token = settings.TWITTER_KEY,
        twitter_secret = settings.TWITTER_SECRET,
        oauth_token = request.session['request_token']['oauth_token'],
        oauth_token_secret = request.session['request_token']['oauth_token_secret'],
    )

    # Retrieve the tokens
    authorized_tokens = twitter.get_authorized_tokens()

    # Check if twitter user has a UserProfile
    try:
        profile = UserProfile.objects.get(twitter_username=authorized_tokens['screen_name'])
    except ObjectDoesNotExist:
        profile = None

我解决了我自己的答案。如果它可以帮助其他人,这是解决方案:

在文件 Twython.py 中,我添加了一个新参数oauth_verifier到 Twython 类构造函数。我得到了oauth_verifier值来自callback_url在我的 twitter_thanks 视图中。

In get_authorized_tokens我删除了这行代码:

response = self.client.get(self.access_token_url)

并添加了以下代码:

callback_url = self.callback_url or 'oob'
request_args = urllib.urlencode({'oauth_callback': callback_url, 'oauth_verifier':self.oauth_verifier })
response = self.client.post(self.access_token_url, params=request_args)

现在它就像一个魅力,并且符合 OAuth 1.0A。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Twython 将 oauth_callback 值传递给 oauth/request_token 的相关文章

随机推荐