Google quickstart.py 由于 JSONDecodeError:额外数据而无法连接到 Google Workspace API



我按照https://developers.google.com/gmail/api/quickstart/python中的步骤创建可以打印Gmail用户标签的示例应用程序。当我执行quickstart.py时,我得到了JSONDecodeError: Extra data。参见错误下面。

最终目标是自动发送电子邮件发票。但是,我不熟悉底层概念,而且没有工作示例,我特别不清楚如何进行。

原始问题关于a)如何解决问题或b)更好的资源来学习所涉及的概念有什么建议吗?

的决议当我删除在credentials.json文件末尾发现的无关的ND时,JSONDecoderError问题消失了。我不知道它是怎么来的;

后续评论

@DaImTo在他们的回答中指出,教程的示例代码是针对已安装的应用程序的,而"对于google工作空间自动化,您将希望使用一个服务帐户并配置域范围委托,以在您的工作空间帐户上设置一个虚拟用户"。请参阅他们的回答,以获得更深入的解释和建议的服务帐户授权代码。

修正credentials.json文件后,出现了一个新的问题。我不会在这里讨论这个问题,因为根据@DaImTo的回答,教程不是创建谷歌工作空间自动化的正确模板。

未来更新

我将根据@DaImTo的建议更新我的进展情况;可以在问题正文中,也可以作为评论或链接。

的错误
Traceback (most recent call last):
File "C:UsersMiranda and WarrenDocumentsInvoiceInvoicingquickstart.py", line 56, in <module>
main()
File "C:UsersMiranda and WarrenDocumentsInvoiceInvoicingquickstart.py", line 30, in main
flow = InstalledAppFlow.from_client_secrets_file(
File "C:UsersMiranda and WarrenDocumentsInvoiceInvoicingNDISlibsite-packagesgoogle_auth_oauthlibflow.py", line 205, in from_client_secrets_file
client_config = json.load(json_file)
File "C:Python310libjson__init__.py", line 293, in load
return loads(fp.read(),
File "C:Python310libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:Python310libjsondecoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 406 (char 405)

教程代码

我从他们的启动指南中复制并粘贴的quickstart.py代码如下:

from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
return
print('Labels:')
for label in labels:
print(label['name'])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')

if __name__ == '__main__':
main()

我按照"为桌面应用程序授权凭据"的步骤操作。以下是我机器上的编辑JSON。请注意文件末尾的'ND'。

(Invalid) credentials.json的内容

{
"installed": {
"client_id": "[46 characters here].apps.googleusercontent.com",
"project_id": "ndis-automation",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "[6 characters]-[7 characters]-[20 characters]",
"redirect_uris": ["http://localhost"]
}
}ND

额外数据:第一行第406列

可能是由无效的凭据引起的。Json文件,看看它是什么样子会很有趣。

你的问题应该是什么😁

最终目标是自动发送发票。

如果你想使用gmail自动与谷歌工作空间,那么这个教程是不会帮助你的。

该教程中的授权方法适用于已安装的应用程序。对于google工作空间自动化,你会想要使用一个服务帐户,并配置域范围授权,在你的工作空间帐户上说一个虚拟用户。

服务帐户授权的代码不同,您需要将主题设置为您已配置委托的域上的用户。

from google.oauth2 import service_account
from googleapiclient.discovery import build
credentials = service_account.Credentials.from_service_account_file(
credentials_file,
scopes=['https://www.googleapis.com/auth/gmail.send'])
impersonate = 'no-reply@daimto.com'
credentials = credentials.with_subject(impersonate)
service = build('gmail', 'v1', credentials=credentials)

最新更新