通过 Google 日历创建活动 API- 授权问题
Creating an event via the Google Calendar API- authorization problem
我正在研究如何使用 API 和 Python 在 Google 日历上创建活动。我得到了 quickstart code to work, but I am having trouble with the event creation.
我尝试在快速启动函数的末尾添加事件创建代码,只是将日期移动到更接近今天的轻微变化,这样我可以更轻松地检查结果,以及范围的变化在“创建活动”页面中提到。这是我的代码:
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.">
有人知道我做错了什么吗?
403 "Request had insufficient authentication scopes."
错误消息不言自明。但是,由于您正在为您想要执行的操作使用适当的范围,因此问题来自 token.pickle 文件。
如果你运行先Quickstart然后直接修改你的脚本而不删除token.pickle文件, 那么这个错误信息是意料之中的。
如何解决这个问题?只要删除token.pickle文件只要您修改请求的范围。
参考
我正在研究如何使用 API 和 Python 在 Google 日历上创建活动。我得到了 quickstart code to work, but I am having trouble with the event creation.
我尝试在快速启动函数的末尾添加事件创建代码,只是将日期移动到更接近今天的轻微变化,这样我可以更轻松地检查结果,以及范围的变化在“创建活动”页面中提到。这是我的代码:
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.">
有人知道我做错了什么吗?
403 "Request had insufficient authentication scopes."
错误消息不言自明。但是,由于您正在为您想要执行的操作使用适当的范围,因此问题来自 token.pickle 文件。
如果你运行先Quickstart然后直接修改你的脚本而不删除token.pickle文件, 那么这个错误信息是意料之中的。
如何解决这个问题?只要删除token.pickle文件只要您修改请求的范围。