使用twython-django登录Twitter

我希望用户可以选择使用他的Twitter帐户登录以获取他的时间表 . 我正在使用twython-django包 . 这是我的代码views.py

def login(request):
twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET)

# Request an authorization url to send the user to...
callback_url =' http://127.0.0.1:8000/cloud/twitter_authenticated/'
auth_props = twitter.get_authentication_tokens(callback_url)

# Then send them over there, durh.
request.session['request_token'] = auth_props

request.session['next_url'] = request.GET.get('next',None)

return HttpResponseRedirect(auth_props['auth_url'])


def twitter_authenticated(request):
"""A user gets redirected here after hitting Twitter and authorizing your app to use their data.
This is the view that stores the tokens you want
for querying data. Pay attention to this.
"""
# Now that we've got the magic tokens back from Twitter, we need to exchange
# for permanent ones and store them...
oauth_token = request.session['request_token']['oauth_token']
oauth_token_secret = request.session['request_token']['oauth_token_secret']
twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET,
                  oauth_token, oauth_token_secret)

# Retrieve the tokens we want...
authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier'])

# If they already exist, grab them, login and redirect to a page displaying stuff.
try:
    user = User.objects.get(username=authorized_tokens['screen_name'])
except User.DoesNotExist:
    # We mock a creation here; no email, password is just the token, etc.
    user = User.objects.create_user(authorized_tokens['screen_name'], "fjdsfn@jfndjfn.com", authorized_tokens['oauth_token_secret'])
    profile = TwitterProfile()
    profile.user = user
    profile.oauth_token = authorized_tokens['oauth_token']
    profile.oauth_secret = authorized_tokens['oauth_token_secret']
    profile.save()

user = authenticate(
    username=authorized_tokens['screen_name'],
    password=authorized_tokens['oauth_token_secret']
)
login(request, user)
redirect_url = request.session.get('next_url', redirect_url)

HttpResponseRedirect(redirect_url)

我收到这个错误:“Twitter API返回401(未经授权),b'不能验证你 . ”

知道如何解决这个问题吗?

回答(0)