Python:使用 Google Calendar API 列出日历

问题描述 投票:0回答:1

我正在尝试使用日历 API 列出我帐户的 Google 日历,但它正在返回

No Calendars Found

下面是我的代码:

models/cal_setup.py

import pickle
import os.path
from google.oauth2 import service_account
from googleapiclient.discovery import build
from google.auth.transport.requests import Request

# You can change the scope of the application, make sure to delete token.pickle file first
SCOPES = ['https://www.googleapis.com/auth/calendar']

CREDENTIALS_FILE = 'credentials.json'     # Give path to your credentials.json file


def get_calendar_service():

    cred = None

    '''
    The file token.pickle stores the user's access and refresh tokens, and is created automatically when
    the authorization flow completes for the first time. In other words when the user give access to this 
    channel
    '''

    if os.path.exists('token.pickle'):
        with open('token.pickle','rb') as token:
            cred = pickle.load(token)
    if not cred or not cred.valid:
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())
        else:
            cred = service_account.Credentials.from_service_account_file(CREDENTIALS_FILE, scopes=SCOPES)
        with open('token.pickle', 'wb') as token:
            pickle.dump(cred, token)
    service = build('calendar','v3',credentials=cred)
    return service

calendar.py

from models.cal_setup import get_calendar_service

def list_cal():

    print("List all calendar")
    service = get_calendar_service()

    print('Getting list of calendars')
    calendars_result = service.calendarList().list().execute()

    calendars = calendars_result.get('items', [])

    if not calendars:
        print('No calendars found.')
    for calendar in calendars:
        summary = calendar['summary']
        id = calendar['id']
        primary = "Primary" if calendar.get('primary') else ""
        print("%s\t%s\t%s" % (summary, id, primary))

list_cal()

我使用从 Google Cloud 服务帐户生成的密钥来实现此目的,以下是其权限:

我已将我的电子邮件帐户添加为所有者。

有人可以帮我吗?

python google-calendar-api google-workspace google-api-python-client service-accounts
1个回答
0
投票

更正您正在尝试列出当前存储在 calendarList 中的日历。这是谷歌日历网站的左下角核心。默认情况下,除了用户主日历之外,除非您手动添加它,否则什么都没有。

您正在使用服务帐户,默认情况下它的日历列表中没有任何内容。您需要委托给工作区域中的用户,以便它将列出该用户已添加到其日历列表中的日历。

100% 清晰的日历列表不会为您提供用户有权访问的所有日历的列表。没有任何方法可以做到这一点。您可以访问日历,但它不会出现在您的日历列表中。

代表团

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE_PATH,
    scopes=SCOPES)

credentials = credentials.create_delegated(user_email) # user to delegate as

return build("calendar", "v3", credentials=credentials)
© www.soinside.com 2019 - 2024. All rights reserved.