调用GMAIL API时出现间歇性错误“调用者没有权限”

2024-04-26 04:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

间歇性地获取此错误

HttpError 403 when requesting https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest returned "The caller does not have permission"

有时有效,有时无效。我在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)

Tags: httpscomclienttokennonelabelswwwservice
2条回答

我也面临着这个最近才出现的问题。我已经使用GMAIL API一年多了,我从来没有遇到过这个问题。我不知道是我们这边有问题还是Gmail改变了他们的使用政策。但是,不管怎样,我还是设法找到了解决办法。我遇到的主要问题是我的信用卡(在你的例子中是谷歌的信用卡)已经过期,每次过期我都必须刷新它们。因此,一个简单的解决方案就是刷新它们

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

我的母语是python,所以我用同一种语言编写了代码,但是您可以在here上看到与您的母语类似的东西

多谢各位

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

-rw-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

相关问题 更多 >