我使用企业 Google Workspace 帐号创建了一个服务帐号,我需要使用 Python 自动创建日历邀请。
我已将服务帐户电子邮件添加到日历的共享人员中,当我尝试使用
service.calendarList().list().execute()
获取日历时,它工作正常。
但是,如果我尝试使用以下代码发送邀请:
def create_invite(self):
event = {
"summary": "Google I/O 2015",
"location": "800 Howard St., San Francisco, CA 94103",
"description": "A chance to hear more about Google's developer products.",
"start": {
"dateTime": "2023-09-16T09:00:00-07:00",
"timeZone": "America/Los_Angeles",
},
"end": {
"dateTime": "2023-09-16T17:00:00-07:00",
"timeZone": "Indian/Mauritius",
},
"attendees": [{"email": "[email protected]"}],
}
event = self.service.events().insert(calendarId=self.id, body=event).execute()
print(f"EVENT: {event}")
它不起作用,我收到以下错误:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/xxxxxx%40group.calendar.google.com/events?alt=json returned "You need to have writer access to this calendar.". Details: "[{'domain': 'calendar', 'reason': 'requiredAccessLevel', 'message': 'You need to have writer access to this calendar.'}]">
查看文档我发现我需要将域范围的权限委托给服务帐户才能正常工作,但由于安全问题,我的公司不允许此服务帐户具有此类访问权限。
所以我想知道是否有任何方法可以在不委托域范围内访问此服务帐户的情况下执行此操作?或者甚至是一种将此类访问权限委托给服务帐户的安全方法?
我要检查的第一件事是您是否具有正确的范围事件。插入需要其中一个
之后我会检查您是否已正确委托给域中的用户。这是通过使用该用户域电子邮件地址调用
create_delegated
来完成的。
然后我会检查以确保该用户有权访问日历
calendarId=self.id
。
def create_calendar_service(user_email):
"""Build and return a calendar service object authorized with the service
account that acts on behalf of the given user.
Args:
user_email: The email of the user to impersonate. Needs permissions to access Cloud Search.
Returns:
calendar API service object that is ready to make requests.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_FILE_PATH,
scopes=SCOPES)
credentials = credentials.create_delegated(user_email)
return build("calendar", "v3", credentials=credentials)