Pydrive:防止 Google 驱动器授权过期。

Pydrive: Preventing Google Drive Authorization from expiring.

在 Google Colab notebook 中,我是 运行 一段代码,需要几个小时才能完成,最后一个文件将上传到我的 Google驾驶。

问题是有时我的凭据会在代码上传文件之前过期。我环顾四周,可能发现了一些可以刷新我的凭据的代码,但我并不是 100% 熟悉 Pydrive 的工作原理以及这段代码究竟在做什么。

这是我目前用来设置我的笔记本以访问我的 Google 驱动器的代码。

!pip install -U -q PyDrive

from google.colab import files
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

这是我用来上传文件的代码

uploadModel = drive.CreateFile()
uploadModel.SetContentFile('filename.file')
uploadModel.Upload()

这是我找到的可以解决我的问题的代码(在此处 PyDrive guath.Refresh() and Refresh Token Issues 找到)

if gauth.credentials is None:
    # Authenticate if they're not there
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # Refresh them if expired
    print "Google Drive Token Expired, Refreshing"
    gauth.Refresh()
else:
    # Initialize the saved creds
    gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("GoogleDriveCredentials.txt")

所以我猜 gauth.Refresh() 行防止我的凭据过期?

当用户验证您的应用程序时。您将获得一个访问令牌和一个刷新令牌。

访问令牌用于访问 Google API。如果您需要访问用户拥有的私人数据,例如他们的 google 驱动器帐户,您需要他们的许可才能访问它。访问令牌的诀窍是它们的寿命很短,只能工作一个小时。一旦访问令牌过期,它将不再起作用,这就是刷新令牌发挥作用的地方。

只要用户不撤销您对您的应用程序通过其 google 帐户访问其数据的同意,刷新令牌大部分不会过期您可以使用刷新令牌请求新的访问令牌.

这就像 elif gauth.access_token_expired: 检查访问令牌是否已过期或可能即将过期。如果是,则 gauth.Refresh() 将刷新它。只需确保您有 get_refresh_token: True,这样您就有一个刷新令牌

我有点惊讶图书馆没有自动为您做这件事。但是我对 Pydrive 不熟悉。 Google APIs Python client library 会自动为您刷新访问令牌。