为什么我在这里得到 KeyError?
Why am I getting KeyError here?
我正在尝试获取日历中所有事件的标题,所以这是我从 Google website
中获取的代码
我的代码:
from Google import Create_Service
import datetime
CLIENT_SECRET_FILE = "secret.json"
API_NAME = 'calendar'
API_VERSION='v3'
SCOPES = ['https://www.googleapis.com/auth/calendar']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
sample = service.events()
page_token = None
while True:
events = sample.list(calendarId='myemail@gmail.com', pageToken=page_token).execute()
for event in events['items']:
print(event['summary'])
page_token = events.get('nextPageToken')
if not page_token:
break
我得到的输出:
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
KeyError Traceback (most recent call last)
Input In [3], in <module>
3 events = sample.list(calendarId='myemail@gmail.com', pageToken=page_token).execute()
4 for event in events['items']:
----> 5 print(event['summary'])
6 page_token = events.get('nextPageToken')
7 if not page_token:
KeyError: 'summary'
它在前几个事件中运行良好。怎么回事?
您的错误告诉您检索到的事件没有 summary
键。我不确定 event
对象到底是什么样子,但是您可以通过首先检查密钥是否存在来避免这样的错误:
page_token = None
while True:
events = sample.list(calendarId='myemail@gmail.com', pageToken=page_token).execute()
for event in events['items']:
# .get() returns None instead of throwing an error,
# or, as I've done in this case, returns a default variable: "No summary found!"
summary = event.get("summary", "No summary found!")
print(summary)
page_token = events.get('nextPageToken')
if not page_token:
break
我正在尝试获取日历中所有事件的标题,所以这是我从 Google website
中获取的代码我的代码:
from Google import Create_Service
import datetime
CLIENT_SECRET_FILE = "secret.json"
API_NAME = 'calendar'
API_VERSION='v3'
SCOPES = ['https://www.googleapis.com/auth/calendar']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
sample = service.events()
page_token = None
while True:
events = sample.list(calendarId='myemail@gmail.com', pageToken=page_token).execute()
for event in events['items']:
print(event['summary'])
page_token = events.get('nextPageToken')
if not page_token:
break
我得到的输出:
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
Holiday
KeyError Traceback (most recent call last)
Input In [3], in <module>
3 events = sample.list(calendarId='myemail@gmail.com', pageToken=page_token).execute()
4 for event in events['items']:
----> 5 print(event['summary'])
6 page_token = events.get('nextPageToken')
7 if not page_token:
KeyError: 'summary'
它在前几个事件中运行良好。怎么回事?
您的错误告诉您检索到的事件没有 summary
键。我不确定 event
对象到底是什么样子,但是您可以通过首先检查密钥是否存在来避免这样的错误:
page_token = None
while True:
events = sample.list(calendarId='myemail@gmail.com', pageToken=page_token).execute()
for event in events['items']:
# .get() returns None instead of throwing an error,
# or, as I've done in this case, returns a default variable: "No summary found!"
summary = event.get("summary", "No summary found!")
print(summary)
page_token = events.get('nextPageToken')
if not page_token:
break