在没有用户输入的情况下如何在python中对Google日历进行api调用?

时间:2019-03-20 15:47:34

标签: python google-calendar-api

我正在尝试致电Google日历api,并检索我计划的活动。我跟随[quickstart] 1对google calander进行了api调用,而在Windows桌面上,它打开了一个网络浏览器,并要求我登录的google帐户进行访问,在我的centos服务器上,它打开了某种形式获取用户信息的流程,但是文本全是德语,所以我真的不明白发生了什么,无论如何,我试图在没有用户输入的情况下对google日历进行api调用,我已经获得了他们的客户ID和客户机密,是否有任何示例或良好指南可以说明我该如何做?我已经看到并了解Google誓言2,0的工作原理,但是我只是看不到我应该如何将其放入代码中。示例代码如下。

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.readonly']

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()
        # 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'))
        end = event['end'].get('dateTime', event['end'].get('date'))
        print(start, event['summary'], end)

if __name__ == '__main__':
    main()

0 个答案:

没有答案