ber*_*eal 4 python google-api-python-client gmail-api
我正在尝试使用Google API Python 客户端和服务帐户身份验证来访问我们的 GSuite GMail API。根据文档,我的 MCVE 代码如下:
import os
import sys
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
email = sys.argv[1]
cred = Credentials.from_service_account_file(os.getenv('SERVICE_ACCOUNT'))
cred = cred.with_scopes(['https://www.googleapis.com/auth/gmail.labels'])
cred.refresh(Request())
gmail = build('gmail', 'v1', credentials=cred)
try:
print(gmail.users().labels().list(userId=email).execute())
except Exception as ex:
print('Error:', ex.content.decode('ascii'))
Run Code Online (Sandbox Code Playgroud)
输出是:
Error: {
"error": {
"errors": [
{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
Run Code Online (Sandbox Code Playgroud)
普通嫌疑犯:
另一个观察结果:当我访问 API 时,服务帐户的使用计数器会增加,但相应的 OAuth2 客户端的使用计数器仍为 0。
我还能缺少什么?
缺少的是文档中提到的一小部分。除了设置范围之外,我还需要通过调用来模拟用户帐户with_subject:
cred = cred.with_subject(email)
Run Code Online (Sandbox Code Playgroud)
之后它就按预期工作了,希望对某人有所帮助。