使用 Python 和 Google Drive API 防止 Google API 令牌过期?

laz*_*rea 3 python google-api google-drive-api

我有以下示例代码,尝试访问我的个人 Google 云端硬盘帐户上的文件。早期版本有一个恼人的问题,即谷歌每次运行时都需要通过在浏览器中打开链接来手动启用它。这就是为什么我通过包含 Oauth2 来修改代码,并相信它会永远解决这个问题。然而今天,我再次发现以下控制台消息:

File "c:\...\site-packages\oauth2client\client.py", line 819, in _do_refresh_request
    raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Token has been expired or revoked.
Run Code Online (Sandbox Code Playgroud)

我相信if not credentials下面代码中的条件的目的是专门根据client_secrets文件自动更新凭据,从而防止此类手动启用。

完整代码如下:

from googleapiclient.discovery import build
from oauth2client import client, tools 
from oauth2client.file import Storage

api_client_secret = r"C:\...\client_secret_0123456789-abc123def456ghi789.apps.googleusercontent.com.json"
credential_file_path = r"C:\...\credential_sample.json"

class GoogleDriveAccess:

    def __init__(self):
        self.service = self.get_authenticated_service(api_client_secret, credential_file_path, 'drive', 'v3', ['https://www.googleapis.com/auth/drive'])

    def get_authenticated_service(self, client_secret_file_path, credential_file_path, api_name, api_version, scopes):
        store = Storage(credential_file_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(client_secret_file_path, scopes)
            credentials = tools.run_flow(flow, store)
        return build(api_name, api_version, credentials=credentials)

if __name__ == '__main__':
    GoogleDriveAccess()
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?如何确保 Google 不会自动撤销我对我自己的 Google 帐户的访问权限?

DaI*_*mTo 5

处于测试阶段的应用程序的刷新令牌将在 7 天后过期。

刷新令牌过期

为外部用户类型配置 OAuth 同意屏幕且发布状态为“测试”的 Google Cloud Platform 项目将获得一个刷新令牌,该令牌将在 7 天后过期。

将您的应用程序投入生产,它不会过期

在此输入图像描述

或者考虑切换到服务帐户

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
Run Code Online (Sandbox Code Playgroud)