如何使用服务帐户为googlecalendarapi构建服务?

2024-06-28 19:15:58 发布

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

我使用OAuth2.0和Google服务帐户来尝试和管理日历。下面提供了Python中的示例代码:

from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build

client_email = "<service_account_client_email>"
with open("key.p12") as f:
    priv_key = f.read()

cred = SignedJwtAssertionCredentials(client_email, priv_key, "https://www.googleapis.com/auth/calendar", sub="<user_to_impersonate>")
http_auth = cred.authorize(Http())

service = build(serviceName='calendar', version='v3', http=http_auth)

到目前为止,我在运行代码时得到了一个异常“required client not authorized”。

我遵循了谷歌文档中的步骤:

  1. 将全域权限委派给您的服务帐户(我创建了服务帐户,但我不是域的管理员)。但是,管理员用户执行了此步骤)。在
  2. 已验证范围是否设置为使用日历,并且在开发人员控制台中启用了API。在
  3. 已与服务帐户共享日历(尽管无法使用管理日历的选项)。在

我错过了什么步骤?我的范围仅仅用于构建服务是否不正确?


Tags: key代码fromimportbuildclientauthhttp