googleapiclient构建失败时捕获401错误?

时间:2019-05-21 17:02:08

标签: google-api-client google-api-python-client

当用户在不通知我们的情况下将我的应用作为第三方应用删除时,我目前正试图抓住一个极端的情况。我目前不知道Google会以任何方式让我知道令牌是否已被撤销,直到我得到google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}')

在我对用户进行身份验证之前,我曾尝试过手动“ ping” Google客户端,但这似乎比仅捕获并处理错误时要慢一些。我也尝试过直接导入auth错误。 import google.auth.exceptions.RefreshError as AuthError

获取凭据:

storage = Storage(GCalUser, 'gcal_user', request.user, 'credentials')
user_credentials = storage.get()

实际通话:

try:
    calendar_service = googleapiclient.discovery.build('calendar', 'v3', credentials=user_credentials)
    print("Error 2: " + str(calendar_service))
except calendar_service:
    pass

如果身份验证有错误,则寻找将用户定向到其他页面的方法。目前,它仅因google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}')

而失败

1 个答案:

答案 0 :(得分:0)

修复了从模块from google.auth.exceptions import RefreshError显式完全导入错误的问题。事实证明,该错误不是在使用用户凭据进行构建时引发的,而是在使用api执行时引发的。

try:
    calendar_list = calendar_service.calendarList().list(pageToken=page_token, minAccessRole="writer").execute()
except RefreshError:
    print("Hello debugging!")