web-dev-qa-db-ja.com

PythonとGoogleカレンダーAPIを使用してGoogleカレンダーイベントを作成する方法

クイックスタート( https://developers.google.com/google-apps/calendar/quickstart/python )から始めましたが、うまくいきました。次に、このガイドでイベントを挿入しようとしました( https://developers.google.com/google-apps/calendar/create-events )。このコードをクイックスタートのコードに追加したところ、エラーが発生しました。 Googleカレンダーにイベントを挿入するためのコードはどのように表示されますか?

だからこれは私のコードです:

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

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'
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 = oauth2client.file.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)

    # Refer to the Python quickstart on how to setup the environment:
    # https://developers.google.com/google-apps/calendar/quickstart/python
    # Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
    # stored credentials.

    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': '2016-09-28T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'end': {
        'dateTime': '2016-09-28T17:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'recurrence': [
        'RRULE:FREQ=DAILY;COUNT=2'
      ],
      'attendees': [
        {'email': '[email protected]'},
        {'email': '[email protected]'},
      ],
      '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 "C:/Users/demin.va/Documents/Dropbox/Programming/Google calendar API/google calendar api.py", line 96, in <module>
    main()
  File "C:/Users/demin.va/Documents/Dropbox/Programming/Google calendar API/google calendar api.py", line 92, in main
    event = service.events().insert(calendarId='primary', body=event).execute()
  File "C:\Users\demin.va\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\demin.va\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, 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">
7
Viktor Demin

問題はフォルダ「.credentials」にありました。クイックスタートの例を前回開始した後、削除しませんでした

SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'  

このフォルダを削除したところ、プログラムは動作します。今だから

SCOPES = 'https://www.googleapis.com/auth/calendar'  
5
Viktor Demin