【发布时间】:2015-03-02 12:09:20
【问题描述】:
我正在使用谷歌官方 oauth2client.client 访问谷歌 加上api。我有一个存储在数据库中的刷新令牌(不会过期),并且需要 从中重新创建临时“凭据”(访问令牌)。
但我无法通过谷歌提供的官方图书馆找到一种方法。
所以我绕过它:使用 urllib 访问 API,它给了我一个新的 来自 refresh_token 的 access_token。使用 access_token 我可以使用该库。
我一定是错过了什么!
from apiclient import discovery
from oauth2client.client import AccessTokenCredentials
from urllib import urlencode
from urllib2 import Request , urlopen, HTTPError
import json
# ==========================================
def access_token_from_refresh_token(client_id, client_secret, refresh_token):
request = Request('https://accounts.google.com/o/oauth2/token',
data=urlencode({
'grant_type': 'refresh_token',
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token
}),
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
)
response = json.load(urlopen(request))
return response['access_token']
# ==========================================
access_token = access_token_from_refresh_token(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)
# now I can use the library properly
credentials = AccessTokenCredentials(access_token, "MyAgent/1.0", None)
http = credentials.authorize(httplib2.Http())
service = discovery.build('plus', 'v1', http=http)
google_request = service.people().get(userId='me')
result = google_request.execute(http=http)
【问题讨论】:
-
嗨,您是否找到了在使用 AccessTokenCredentials 时刷新令牌的解决方案?我正在尝试找出如何做到这一点,但周围没有可见的文档......
-
只是为了在历史上有所作为,以防其他人撞到墙上:Google 的文档在这里很复杂(或不完整)。
AccessTokenCredentials不提供刷新令牌的方法。因此,您需要使用其他类型的凭据,正如以下答案中所解释的那样,我可以使用以下两个可能的选项:OAuth2Credentials和GoogleCredentials(GoogleCredentials扩展OAuth2Credentials)。
标签: python google-api google-plus