我正在创建一个脚本,该脚本将使用模拟特定 Google Apps 用户的服务帐户下载该用户的所有文件(使用提供的 Python 模板代码 here(请参阅下面的代码块)。
def createDriveService(user_email):
"""Build and returns a Drive service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user.
Returns:
Drive service object.
"""
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope='https://www.googleapis.com/auth/drive', prn=user_email)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
我已经能够使用此功能成功进行身份验证,并且可以执行下载、文件列表请求等。但是,如果我尝试在短时间内执行四次以上的下载,则会收到以下错误:
Traceback (most recent call last):
// snip //
File "C:\***\changeScan2.py", line 48, in createDriveService
return build('drive', 'v2', http=http)
File "build\bdist.win32\egg\oauth2client\util.py", line 120, in positional_wrapper
File "build\bdist.win32\egg\apiclient\discovery.py", line 193, in build
File "build\bdist.win32\egg\oauth2client\util.py", line 120, in positional_wrapper
File "build\bdist.win32\egg\oauth2client\client.py", line 405, in new_request
File "build\bdist.win32\egg\oauth2client\client.py", line 573, in _refresh
File "build\bdist.win32\egg\oauth2client\client.py", line 629, in _do_refresh_request
oauth2client.client.AccessTokenRefreshError: Invalid response 403
程序成功获取要下载的文件列表 (files.list),下载四个文件(每次都进行身份验证),然后在第五次下载时出现上述错误。整个过程需要5-10秒。在多次运行不同文件时,程序在下载第五个文件的过程中返回错误。
我将应用程序精简为最基本的功能,尝试下载不同的文件,但收到了相同的错误。我 try catch 异常并为 createDriveService 函数实现指数退避,但错误似乎位于 Google API 客户端文件中,因此我无法缓解它。 Here's查看 oauth2client\client.py 代码的链接似乎给我带来了问题。
有什么想法吗?
最佳答案
在您获取 SignedJwtAssertionCredentials 私钥的 API 控制台中,该页面底部还有一个 API key 。将该API key 作为developerKey参数传递给discovery.build()函数:
http://google-api-python-client.googlecode.com/hg/docs/epy/apiclient.discovery-module.html#build
当您达到配额限制(每日总限制或短期限制)时,将返回 403 响应。由于云端硬盘的每日礼貌配额限制为每天 500,000 个请求,我认为您没有达到该限制,但您可能需要添加该 API key ,以便真正获得完整配额。
我最近对客户端库进行了更改,以便更好地处理 403 错误,这还没有出现在发布的版本中,但是如果您从 head 中拉出,您实际上会看到 403 是一个异常,应该会有关调用失败原因的完整信息。
关于google-drive-api - 来自 oauth2client 的 "AccessTokenRefreshError: Invalid Response 403",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14246347/