调用GMAIL API时出现间歇性错误 - "调用方没有权限"

9

有时候会出现以下错误:

请求 https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest 时出现 HttpError 403 错误,返回信息为“调用者没有权限”

有时候可以正常工作,有时候不行。我在 OAuth2 Playground 上也遇到了同样的问题。

这是我的代码 -

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)

我能看到一个刷新令牌。你可能会使用过期的令牌吗?因为你说有时它可以工作。 - Snigdhajyoti
我强制刷新了浏览器 - ctrl+F5。它起作用了。 - Aseem
2
你好!这种情况是否只发生在你的账户中?你认为它发生的频率是多少?另外,在刷新页面后,OAuth2 playground 中是否仍然出现此问题?已有类似的行为被报告为错误 here,请查看以确定您的情况是否相似或相同,如果是,请添加 +1 表示您正在经历相同的行为。 - Mateo Randwolf
你好!已经报告的错误已经被修复了,你还遇到同样的问题吗?还是这个修复方案也解决了你的问题? - Mateo Randwolf
2个回答

1
我最近也遇到了这个问题。我已经使用GMAIL API超过一年了,以前从未遇到过这个问题。我不知道是我们的问题还是Gmail更改了使用政策。但是,无论如何,我成功找到了解决方案。我遇到的主要问题是我的凭据(您的情况下的谷歌凭据)过期了,每次过期后都需要刷新它们。因此,一个简单的解决方案就是刷新它们。
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())

我的母语是Python,所以我用相同的语言编写了代码,但您可以前往此处查看您母语中类似的内容。

谢谢。


0

我也突然看到了这个问题。 几个月来一切都正常,代码没有更改。 还看到令牌正在刷新。

-rw-r--r-- 1 kosalanbalarajah staff 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接