Skip to main content
 首页 » 编程设计

python之Pydrive:防止 Google Drive 授权过期。

2024年12月31日8bonelee

在 Google Colab 笔记本中,我正在运行一段需要几个小时才能完成的代码,最后一个文件将上传到我的 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() 行可以防止我的凭据过期?

请您参考如下方法:

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

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

只要用户不取消您对您的应用程序通过其 Google 帐户访问其数据的同意,刷新 token 在大多数情况下都不会过期,您可以使用刷新 token 来请求新的访问 token 。

这类似于 elif gauth.access_token_expired: 检查访问 token 是否已过期或可能即将过期。如果是,则 gauth.Refresh() 将刷新它。只要确保你有 get_refresh_token: True 这样你就有一个刷新 token

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