我試圖從使用OAuth的python應用程序中獲取Gmail atom feed。我有一個可以下載谷歌閱讀器提要的工作應用程序,我認爲應該是只是一個改變範圍和提要URL的問題。替換URL後,我仍然可以成功獲取請求和訪問令牌,但是當我嘗試使用Access令牌獲取Feed時,出現「401未授權」錯誤。這是我簡單的測試程序:使用OAuth訪問Gmail原子提要
import urlparse
import oauth2 as oauth
scope = "https://mail.google.com/mail/feed/atom/"
sub_url = scope + "unread"
request_token_url = "https://www.google.com/accounts/OAuthGetRequestToken?scope=%s&xoauth_displayname=%s" % (scope, "Test Application")
authorize_url = 'https://www.google.com/accounts/OAuthAuthorizeToken'
access_token_url = 'https://www.google.com/accounts/OAuthGetAccessToken'
oauth_key = "anonymous"
oauth_secret = "anonymous"
consumer = oauth.Consumer(oauth_key, oauth_secret)
client = oauth.Client(consumer)
# Get a request token.
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']
print
# Step 2: Link to web page where the user can approve the request token.
print "Go to the following link in your browser:"
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
print
raw_input('Press enter after authorizing.')
# Step 3: Get access token using approved request token
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
client = oauth.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
# Access content using access token
token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
client = oauth.Client(consumer, token)
resp, content = client.request(sub_url, 'GET')
print content
你會發現,我使用「匿名/匿名」作爲我的OAuth密鑰/祕密,如Google documents for unregistered applications提及。這適用於谷歌閱讀器,所以我沒有看到任何理由不適用於Gmail。有沒有人有任何想法,爲什麼這可能無法正常工作,或者我怎麼能解決它?謝謝。
有你這個實現自己一個理由?查看http://libgmail.sourceforge.net/。無論如何,這不是你的問題的答案,所以這裏是在評論! – alecwh 2010-07-03 06:51:59
@alecwh:libgmail似乎要求我的程序知道用戶的用戶名和密碼。如果可以,我試圖避免這種情況,這就是爲什麼我想使用oauth。 – Will 2010-07-03 18:56:59