San*_*ta7 5 python google-drive-api google-oauth pydrive
在 Google Colab 笔记本中,我正在运行一段代码,需要几个小时才能完成,最后一个文件将上传到我的 Google 驱动器。
问题是有时我的凭据会在代码上传文件之前过期。我环顾四周,可能发现了一些可以刷新我的凭据的代码,但我并不是 100% 熟悉 Pydrive 的工作原理以及这段代码到底在做什么。
这是我目前用来设置我的笔记本以访问我的 Google Drive 的代码。
!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)
Run Code Online (Sandbox Code Playgroud)
这是我用来上传文件的代码
uploadModel = drive.CreateFile()
uploadModel.SetContentFile('filename.file')
uploadModel.Upload()
Run Code Online (Sandbox Code Playgroud)
这是我找到的可以解决我的问题的代码(在此处找到PyDrive guath.Refresh() 和 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")
Run Code Online (Sandbox Code Playgroud)
所以我猜这gauth.Refresh()条线会阻止我的凭据过期?
When a user authenticates your application. You are given an access token and a refresh token.
Access tokens are used to access the Google APIs. If you need to access private data owned by a user for example their google drive account you need their permission to access it. The trick with access tokens is they are short lived they work for an hour. Once the access token has expired it will no longer work and this is where the refresh token comes into play.
只要用户不取消您对应用程序通过其 Google 帐户访问其数据的同意,刷新令牌在大多数情况下就不会过期,您可以使用刷新令牌来请求新的访问令牌。
这类似于elif gauth.access_token_expired:检查访问令牌是否已过期或可能即将过期。如果是的话gauth.Refresh()就会刷新它。只需确保您拥有get_refresh_token: True刷新令牌即可
我有点惊讶图书馆没有自动为你做这件事。但我对 Pydrive 不熟悉。Google API Python 客户端库会自动为您刷新访问令牌。