首页 > 解决方案 > 通过 Google Calendar API 创建事件 - 授权问题

问题描述

我正在尝试研究如何使用 API 和 Python 在 Google 日历上创建事件。我得到了快速入门代码,但我在创建事件时遇到了问题。

我试图在快速启动函数的末尾添加事件创建代码,只是将日期移动到更接近今天的轻微更改,以便我可以更轻松地检查结果,以及创建事件中提到的范围更改页。这是我的代码:

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

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']


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.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    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:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])
    

    event = {
        'summary': 'Google I/O 2020',
        'location': '800 Howard St., San Francisco, CA 94103',
        'description': 'A chance to hear more about Google\'s developer products.',
        'start': {
            'dateTime': '2020-12-05T09:00:00-07:00',
            'timeZone': 'America/Los_Angeles',
        },
        'end': {
            'dateTime': '2020-12-05T17:00:00-07:00',
            'timeZone': 'America/Los_Angeles',
        },
        'recurrence': [
            'RRULE:FREQ=DAILY;COUNT=2'
        ],
        'reminders': {
            'useDefault': False,
            'overrides': [
                {'method': 'email', 'minutes': 24 * 60},
                {'method': 'popup', 'minutes': 10},
            ],
        },
    }

    event = service.events().insert(calendarId='primary', body=event).execute()
    print( 'Event created: %s' % (event.get('htmlLink')) )



if __name__ == '__main__':
    main()

我得到的错误是:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json returned "Request had insufficient authentication scopes.". Details: "Request had insufficient authentication scopes."> 

有谁知道我做错了什么?

标签: python-3.xauthorizationgoogle-calendar-api

解决方案


403 "Request had insufficient authentication scopes."错误消息是不言自明的。但是,由于您正在使用适当的范围来执行您想要执行的操作,因此问题来自token.pickle文件。

如果您先运行快速入门,然后直接修改脚本而不删除token.pickle文件,则该错误消息是意料之中的。

如何解决这个问题?每当您修改请求的范围时,只需删除token.pickle文件。

参考


推荐阅读