【问题标题】:intermittent error while calling GMAIL API - "The caller does not have permission"调用 GMAIL API 时出现间歇性错误 - “调用者没有权限”
【发布时间】:2020-10-24 07:56:58
【问题描述】:

间歇性出现此错误

请求https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest时HttpError 403返回“调用者没有权限”

有时有效,有时无效。我在 oauth2 游乐场看到了同样的问题

这是我的代码 -

googlecredentials = GoogleCredentials(
    access_token=None,
    client_id='xxx',
    client_secret='xxxx',
    refresh_token='xxxx',
    token_expiry=None,
    token_uri="https://www.googleapis.com/oauth2/v3/token", 
    user_agent='Python client library'
)

service = build('gmail', 'v1', credentials=googlecredentials)

results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
response = service.users().messages().list(userId='me', q='subject:FDA').execute()
print(response)

【问题讨论】:

  • 我可以看到一个刷新令牌。是否有可能您有时会使用过期的令牌,正如您所说的那样它有时会起作用?
  • 我努力刷新了我的浏览器 - ctrl+F5。成功了
  • 嗨!它是否仅在您的帐户中发生?您认为这种情况发生的速度是多少?另外,刷新页面后是否还会出现在 OAuth2 Playground 中?有一个类似的报告行为作为错误here 提交,检查它以查看您的案例是否相似或相同,如果是,请添加 +1 以表明您遇到相同的行为。
  • 嗨! bug that was reported 已经修复,您是否仍然遇到同样的问题,或者此修复也解决了您的问题?

标签: python gmail-api google-oauth google-api-python-client oauth2-playground


【解决方案1】:

我最近也面临这个问题。我已经使用 GMAIL API 一年多了,我从来没有遇到过这个问题。我不知道我们这边是否存在问题或 Gmail 更改了他们的使用政策。但是,无论如何,我确实设法找到了解决方案。我遇到的主要问题是我的信用(在你的情况下是谷歌凭据)已经过期,每次过期我都必须刷新它们。因此,一个简单的解决方案就是刷新它们。

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())

我的母语是 python,所以我用相同的语言编写了代码,但是您可以前往 here 并以您的母语查看类似的内容

谢谢。

【讨论】:

    【解决方案2】:

    我也突然看到了这一点。 几个月来一切都运行良好,代码没有任何变化。 还看到令牌正在刷新。

    -rw-r--r-- 1 kosalanbalarajah 员工 728 Jul 6 12:50 token.pickle

    但错误没有得到解决。

    还有一开始的刷新代码。

    如果没有(有效)凭据可用,让用户登录。

        # If token.pickle does not exist there are no valid token, let user log in again to generate token and save the token for furture use.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(credentialspath, self.SCOPES) # Change credentials.json to credentialspath
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open(tokenpath, 'wb') as token: # Change token.pickle to tokenpath
                pickle.dump(creds, token)
    
        return creds
    

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2021-04-06
      • 1970-01-01
      • 2022-07-13
      • 2018-05-04
      相关资源
      最近更新 更多