Google Calendar API无法获取颜色ID

时间:2018-07-28 12:51:59

标签: python google-api google-calendar-api

基本上,我编写了一个应该显示事件名称的代码,它是十六进制颜色代码,但是由于某些原因,该代码不起作用,并且显示了一个称为Keyerror:colorId的错误。

我看着https://developers.google.com/calendar/v3/reference/colors/get,不知道如何解决这个问题

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime

SCOPES = 'https://www.googleapis.com/auth/calendar'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))

now = datetime.datetime.utcnow().isoformat() + 'Z'
print('Getting the upcoming 10 events and color')
events_result = service.events().list(calendarId='primary', timeMin=now,
                                      maxResults=10, singleEvents=True,
                                      orderBy='startTime').execute()
colors = service.colors().get().execute()

events = events_result.get('items', [])

if not events:
    print('No upcoming events found.')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))
    varv = colors['calendar'][event['colorId']]['background']
    print(start, varv)

1 个答案:

答案 0 :(得分:0)

此修改如何?

修改点:

  • 为了检索事件颜色,请在字段中使用event
  • 也有没有colorId的事件。

修改后的脚本:

为了反映以上几点,请进行以下修改。

来自:
colors = service.colors().get().execute()

events = events_result.get('items', [])

if not events:
    print('No upcoming events found.')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))
    varv = colors['calendar'][event['colorId']]['background']
    print(start, varv)
至 :
colors = service.colors().get(fields='event').execute()  # Modified

events = events_result.get('items', [])

if not events:
    print('No upcoming events found.')
for event in events:
    if 'colorId' in event:  # Added
        start = event['start'].get('dateTime', event['start'].get('date'))
        varv = colors['event'][event['colorId']]['background']  # Modified
        print(start, varv)

参考:

如果这不是您想要的,对不起。