gpt4 book ai didi

python - Google Calendar API 仅获取日历的第一个事件

转载 作者:行者123 更新时间:2023-12-04 07:51:36 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的 python 桌面应用程序来显示我当天的任务。为此,我使用 Google Calendar API 来获取我个人日历的事件。我还应该提到,我是 python 编程的初学者,对 API 本身没有经验,这可能就是我遇到这个问题的原因。
我使用了来自谷歌开发者页面的快速入门代码来获取 API。但由于某种原因,它只返回日历上第一个事件的摘要,当它应该显示前 10 个时。我有一个单独的文件来显示从快速入门返回的数据,但问题不应该在于打印快速入门中的语句也只打印一个事件。
这是我从 Google 的 quickstart.py 中稍微修改的代码:

from __future__ import print_function
import datetime
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials


SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']


def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
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())

service = build('calendar', 'v3', credentials=creds)


# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])


if not events:
print('No upcoming events found.')
for event in events:
time = event['start'].get('dateTime', event['start'].get('date'))
title = event['summary']
# print(event['summary'], time)
return title, time


if __name__ == '__main__':
main()
谷歌开发者 API 引用对我也没有太大帮助,那么有谁知道是什么导致了这个问题?
另外,我如何从所有日历中获取数据,而不仅仅是主要日历?

最佳答案

Execute 按页面返回结果(大小受 maxResults 限制) - 您只看到第一个事件的原因可能是由于 2 个问题:

  • 您只查看结果的第一页
  • 路过singleEvents=True仅返回重复事件的第一个实例。这意味着,如果您的日历有任何重复事件(每天/每周等),您只会在结果中获得该事件的第一次出现。如果您想获取所有事件(据我所知,这就是您想要的)-您需要删除此参数。
    尝试合并以下代码来解决您的问题:
     result = []
    page_token = None

    while True:
    page = service.events().list(calendarId='primary',
    timeMin=now,
    maxResults=10,
    orderBy='startTime',
    pageToken=page_token).execute()
    result.extend(page["item"])
    page_token = page.get('nextPageToken')

    if not page_token:
    break

    return result
  • 关于python - Google Calendar API 仅获取日历的第一个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66943079/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com