python - 谷歌 API : getting Credentials from refresh token with oauth2client. 客户端

标签 python google-api google-plus

我正在使用谷歌官方 oauth2client.client 访问谷歌 加上api。我有一个存储在数据库中的刷新 token (不会过期),并且需要 从中重新创建临时“凭据”(访问 token )。

但我无法通过谷歌提供的官方图书馆找到一种方法。

所以我绕过它:使用 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)

最佳答案

我使用:oauth2client.client.GoogleCredentials

    cred = oauth2client.client.GoogleCredentials(access_token,client_id,client_secret,
                                          refresh_token,expires_at,"https://accounts.google.com/o/oauth2/token",some_user_agent)
    http = cred.authorize(httplib2.Http())
    cred.refresh(http)
    self.gmail_service = discovery.build('gmail', 'v1', credentials=cred)

关于python - 谷歌 API : getting Credentials from refresh token with oauth2client. 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27771324/

相关文章:

python - 在 azure 函数中找不到本地模块

java - 运行示例代码时找不到 URL

android - G+ 登录 Ian Barber 实现 : onConnectionFailed not getting called when disconnecting rebuilding GoogleApiClient

javascript - 如何在没有内容安全策略错误的情况下在内容脚本中使用 Google +1?

ios - Google Plus 无法在 iOS 10 中运行

python - 导入错误 : No module named site

python - 在 sqlite 中存储 GUID 的正确方法

python - 当目标是一个热编码时,随机森林预测任一类

api - Google API - 使用内部 IP 重定向 URI

google-analytics - 使用Google Analytics(分析)API获取 session 的导航路径