我正在尝试制作一个简单的 Python 桌面应用程序来显示我当天的任务。为此,我使用 Google Calendar API 来获取我个人日历的事件。我还应该提到,我是 Python 编程的初学者并且没有 API 本身的经验,这可能就是我遇到这个问题的原因。 我使用了来自 google 开发人员页面的快速入门代码作为 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 参考对我也没有太大帮助,所以有人知道是什么导致了这个问题吗?
另外,我如何从所有日历中获取数据,而不仅仅是主要日历?
答案 0 :(得分:2)
执行按页返回结果(大小受 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