首先,导入oauth2模块 https://github.com/simplegeo/python-oauth2并设置服务的 URL 和消费者信息:
import oauth2
REQUEST_TOKEN_URL = 'http://www.tumblr.com/oauth/request_token'
AUTHORIZATION_URL = 'http://www.tumblr.com/oauth/authorize'
ACCESS_TOKEN_URL = 'http://www.tumblr.com/oauth/access_token'
CONSUMER_KEY = 'your_consumer_key'
CONSUMER_SECRET = 'your_consumer_secret'
consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
client = oauth2.Client(consumer)
步骤 1:获取请求令牌。这是一个临时令牌,用于
让用户授权访问令牌并签署请求以获取
说访问令牌。
resp, content = client.request(REQUEST_TOKEN_URL, "GET")
request_token = dict(urlparse.parse_qsl(content))
print "Request Token:"
print " - oauth_token = %s" % request_token['oauth_token']
print " - oauth_token_secret = %s" % request_token['oauth_token_secret']
第 2 步:重定向至提供商。由于这是一个 CLI 脚本,我们不
重定向。在 Web 应用程序中,您会将用户重定向到 URL
以下。
print "Go to the following link in your browser:"
print "%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token['oauth_token'])
# After the user has granted access to you, the consumer, the provider will
# redirect you to whatever URL you have told them to redirect to. You can
# usually define this in the oauth_callback argument as well.
oauth_verifier = raw_input('What is the PIN? ')
Step 3:一旦消费者将用户重定向回 oauth_callback
您可以请求用户已批准的访问令牌的 URL。您使用
请求令牌来签署此请求。完成此操作后,您扔掉
请求令牌并使用返回的访问令牌。你应该存储这个
访问令牌在安全的地方,例如数据库,以供将来使用。
token = oauth2.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth2.Client(consumer, token)
resp, content = client.request(ACCESS_TOKEN_URL, "POST")
access_token = dict(urlparse.parse_qsl(content))
print "Access Token:"
print " - oauth_token = %s" % access_token['oauth_token']
print " - oauth_token_secret = %s" % access_token['oauth_token_secret']
print
现在您有了访问令牌,您可以用它调用受保护的方法。
EDIT:事实证明,tumblr 不支持 PIN 授权方法。相关帖子.