python - Google Python API 客户端使用refresh_token刷新access_token

标签 python google-api google-api-python-client

好吧,我一直在尝试了解 google python api 客户端库。这就是我所拥有的:

  1. Oauth2Credentials 类 -> 提供刷新方法,允许重新颁发新的 access_token。在客户端中,这是重新发行新 token 的唯一公开可见的方法。此外,如果使用此类的实例授权 http 请求,则将隐式处理刷新。 此外,理想情况下不应直接创建此实例,而应通过流对象创建。 https://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.OAuth2Credentials-class.html

  2. AccessTokenCredentials 类 -> 仅接受 access_token,并且只能用于验证 http 请求。不提供刷新方法。 https://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.AccessTokenCredentials-class.html

当通常不创建 Oauth2Credentials 实例时,如何使用刷新 token 来获取新的 access_token?我应该在第一次生成时存储凭证对象吗?如果是这样怎么办?

最佳答案

是的,您应该以某种方式将访问 token 存储在数据库中。

当您从数据库加载它时,以下是如何在使用它之前实际刷新它:

    #when you load the credentials from the DB, make sure it is 
    #this type of object:
    credentials = google.oauth2.credentials.Credentials()
    #here is the object (with type) that the credential object needs to
    #do the refreshing
    request = google.auth.transport.requests.Request()
    #and now we actually refresh the token.
    credentials.refresh(request)
    #and now the credentials object should be usable.

如果您正在寻找更多详细信息,我已经在此处从头到尾使用 google 库编写了整个 oauth2 流程:

https://stackoverflow.com/a/48242762/1626536

关于python - Google Python API 客户端使用refresh_token刷新access_token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33734389/

相关文章:

Android Pay - 完整的电子钱包确认结果代码 1 和错误代码 10

python - zip() 是 python 中的生成器函数吗?

python - 如何将 .accdb 文件导入 Python 并使用数据?

google-app-engine - 尝试使用 API key 访问 BigQuery 时出错(简单 API 访问)

ruby-on-rails - 在 Rails 应用程序中连接到 Google Analytics API

google-calendar-api - 带有服务帐户的 Google Calendar Python API 不返回任何结果

python - 使用其 API 和 Python 在 Google 表格电子表格中设置单元格格式

python-3.x - 如何模拟 googleapiclient.discovery.build 以单元测试从谷歌表格读取

python - 尝试重命名 tf.keras 上的预训练模型时出错

python - 递归重命名文件以使文件名与其路径串联