![](/img/trans.png)
[英]Get and display event id for Google Calender api (Python)
[英]Google Calender API only fetching first event of calendar
我正在尝试制作一个简单的 python 桌面应用程序来显示我当天的任务。 为此,我使用 Google 日历 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.