用于日历ID的Google Calendar API HttpError 404

时间:2018-03-02 23:09:07

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

我使用的是Google Calendar API Python快速启动代码的修改版本,对我来说很有用。我最近刚买了一台新电脑,并一直在传输文件。现在,当我运行脚本时,我得到一个HTTPError 404.代码如下:

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')

"""Below, I switched out 'primary' with the calendarId of the calendar I 
actually wanted"""

    eventsResult = service.events().list(
        calendarId='redacted@group.calendar.google.com', 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'])

if __name__ == '__main__':
    main()

我注意到当我更换' calendarId'与主要'而不是我想要的日历ID,代码工作正常。我无法弄清楚为什么在这个完全相同的代码在我以前的机器上工作正常时我收到错误消息。这是以下完整的错误消息(编辑):

Traceback (most recent call last):
  File "C:\redacted.py", line 84, in <module>
    main()
  File "C:\redacted.py", line 73, in main
    orderBy='startTime').execute()
  File "C:\redacted\Python\Python36-32\lib\site-
   packages\oauth2client\_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\redacted\Python\Python36-32\lib\site-
    packages\googleapiclient\http.py", line 844, in execute
    raise HttpError(resp, content, uri=self.uri)
  googleapiclient.errors.HttpError: <HttpError 404 when requesting 
    https://www.googleapis.com/calendar/v3/calendars/redacted=json returned 
    "Not Found">

任何人都可以帮助解释我错过的内容吗?

1 个答案:

答案 0 :(得分:0)

应该是使用您的应用的用户的电子邮件地址。此外,如果您要访问除自己以外的其他calendarID,则应该与访问它的用户共享。

  

<强> calendarId

     
      
  • 日历标识符。要检索日历ID,请调用calendarList.list方法。如果要访问当前登录用户的主日历,请使用&#34; primary&#34;关键字。
  •   

见下面的图片:

enter image description here

希望这有帮助。

相关问题