尝试使用Python客户端将ACL插入日历时出现错误404-如果我重试即可使用

时间:2020-06-16 18:50:41

标签: python google-calendar-api google-api-client

使用Google Suite for Education。

我有一个应用程序想要:

  • 创建新日历。
  • 在此类日历中添加ACL,因此学生角色将为“阅读者”。

一切都通过服务帐户运行。

创建日历很好,但是插入ACL会引发404错误(为保护隐私而删除):

<HttpError 404 when requesting https://www.googleapis.com/calendar/v3/calendars/MY_DOMAIN_long_string%40group.calendar.google.com/acl?alt=json returned "Not Found">

试图插入ACL的函数:

    def _create_calendar_acl(calendar_id, user, role='reader'):
        credentials = service_account.Credentials.from_service_account_file(
            CalendarAPI.module_path)
        scoped_credentials = credentials.with_scopes(
            ['https://www.googleapis.com/auth/calendar'])

        delegated_credentials = scoped_credentials.with_subject(
            'an_admin_email')

        calendar_api = googleapiclient.discovery.build('calendar',
                                                       'v3',
                                                       credentials=delegated_credentials)
        body = {'role': role,
                'scope': {'type': 'user',
                          'value': user}}

        answer = calendar_api.acl().insert(calendarId=calendar_id,
                                           body=body,
                                           ).execute()
        return answer

最有趣的是,如果我重试该操作几次,它最终会成功。因此,这就是我的代码所做的:

def create_student_schedule_calendar(email):
    MAX_RETRIES = 5
    # Get student information

    # Create calendar
    answer = Calendar.create_calendar('a.calendar.owner@mydomain',
                                      f'Student Name - schedule',
                                      timezone='Europe/Madrid')

    calendar_id = answer['id']

    counter = 0
    while counter < MAX_RETRIES:
        try:
            print('Try ' + str(counter + 1))
            _create_calendar_acl(calendar_id=calendar_id, user=email)  # This is where the 404 is thrown
            break
        except HttpError:  # this is where the 404 is caught
            counter += 1
            print('Wait ' + str(counter ** 2))
            time.sleep(counter ** 2)
            continue

    if counter == MAX_RETRIES:
        raise Exception(f'Exceeded retries to create ACL for {calendar_id}')

无论如何,成功需要四次尝试(介于14到30秒之间)-有时它会过期。

使用该API的API是否有可能立即无法使用最近创建的日历?

1 个答案:

答案 0 :(得分:1)

传播通常是基于云的服务的问题。大型在线服务是沿着机器网络分布的,这些机器本身具有一定程度的延迟-信息沿着网络传播并在各处更新所花费的时间是离散的,非零的。

在第一次调用后未执行404的所有操作均在此过程中得到说明。

缓解措施:

我建议您是否要在同一函数调用中创建和编辑,以实现某种程度的等待/睡眠以减轻获取404错误的时间。这可以使用时间库在python中完成:

import time
# calendar creation code here
time.sleep(2)
# calendar edit code here

我希望这对您有帮助!

相关问题