[英]How to solve “Insufficient Permission” for userUsageReport with Google API?
[英]How to solve HttpError 403 “Insufficient Permission” in Google calander API?
我想使用python使用Google Calendar API創建事件。 我從這里使用了示例代碼https://developers.google.com/google-apps/calendar/v3/reference/events/insert
我以為GMT是一個問題,但是后來我也更改了GMT,就像使用Google日歷設置的代碼一樣。 但是仍然有相同的錯誤。 完整的代碼如下
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import datetime
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = eventsResult.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 2015',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': '2017-03-24T09:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': '2017-03-24T17:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees': [
{'email': 'lpage@example.com'},
{'email': 'sbrin@example.com'},
],
'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()
錯誤是:
Traceback (most recent call last):
File "D:/cs/projects/googleApi/quickstart.py", line 106, in <module>
main()
File "D:/cs/projects/googleApi/quickstart.py", line 102, in main
event = service.events().insert(calendarId='primary', body=event).execute()
File "D:\cs\anaconda\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "D:\cs\anaconda\lib\site-packages\googleapiclient\http.py", line 840, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json returned "Insufficient Permission">
我是google API的新手。 我發現了一些類似的問題,但它們是針對gmail或其他服務的,但沒有日歷。 該錯誤可能是什么解決方案。 可以請任何人幫忙嗎?
我最初的猜測是,您需要在更改范圍之后生成一個新的訪問令牌。 如果您需要有關Google日歷如何使用Oauth2的更多信息,我已經為類似的問題提供了答案。
實際的解決方案是使用:
SCOPES = 'https://www.googleapis.com/auth/calendar'
然后按照評論:
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
通過進入“〜/ .credentials /”並刪除文件“ calendar-python-quickstart.json”
我有同樣的問題,但解決如下:
正如@Dalm要提到的那樣,您必須將范圍從https://www.googleapis.com/auth/calendar.readonly
更改為https://www.googleapis.com/auth/calendar
,然后刪除.credentials
文件夾中的client_secret.json
文件。 https://www.googleapis.com/auth/calendar
。
請按照以下步驟操作,並確定已解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.