gpt4 book ai didi

python - 使用 Python 和 Google Drive API 防止 Google API token 过期?

转载 作者:行者123 更新时间:2023-12-05 01:55:23 32 4
gpt4 key购买 nike

我有以下示例代码,它试图访问我的个人 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.

我认为下面代码中 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()

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

最佳答案

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

Refresh token expiration

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

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

enter image description here

或者考虑切换到 service account .

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)

关于python - 使用 Python 和 Google Drive API 防止 Google API token 过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70250812/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com