近日做练手的工作日志的项目,想把谷歌日历关联到项目中,启动App后可以在App中获取Google日历的内容(或者同步),但以前没有写过类似的代码,简单GG了下,参考Google官方的文档,稍微做了点改动,成功获取到了当日的日程。
参考:
补充:是官方的Example
代码如下:
1 """ A quickstart example showing usage of the Google Calendar API. """ 2 from datetime import datetime, timedelta 3 import os 4 5 from httplib2 import Http 6 import oauth2client 7 from oauth2client import client 8 from oauth2client import tools 9 10 from apiclient.discovery import build 11 12 try : 13 import argparse 14 15 flags = argparse.ArgumentParser(parents = [tools.argparser]).parse_args() 16 except ImportError: 17 flags = None 18 19 SCOPES = ' https://www.googleapis.com/auth/calendar.readonly ' 20 CLIENT_SECRET_FILE = ' client_secret.json ' 21 APPLICATION_NAME = ' Calendar API Quickstart ' 22 23 def get_credentials(): 24 """ Gets valid user credentials from storage. 25 26 If nothing has been stored, or if the stored credentials are invalid, 27 the OAuth2 flow is completed to obtain the new credentials. 28 29 Returns: 30 Credentials, the obtained credential. 31 """ 32 home_dir = os.path.expanduser( ' ~ ' ) 33 credential_dir = os.path.join(home_dir, ' .credentials ' ) 34 if not os.path.exists(credential_dir): 35 os.makedirs(credential_dir) 36 credential_path = os.path.join(credential_dir, 37 ' calendar-api-quickstart.json ' ) 38 39 store = oauth2client.file.Storage(credential_path) 40 credentials = store.get() 41 if not credentials or credentials.invalid: 42 flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 43 flow.user_agent = APPLICATION_NAME 44 if flags: 45 credentials = tools.run_flow(flow, store, flags) 46 else : # Needed only for compatability with Python 2.6 47 credentials = tools.run(flow, store) 48 print ' Storing credentials to ' + credential_path 49 return credentials 50 51 52 def main(): 53 """ Shows basic usage of the Google Calendar API. 54 55 Creates a Google Calendar API service object and outputs a list of the next 56 10 events on the user's calendar. 57 """ 58 credentials = get_credentials() 59 service = build( ' calendar ' , ' v3 ' , http = credentials.authorize(Http())) 60 61 dateStart = datetime.today().date() 62 dateEnd = dateStart + timedelta(days = 1 ) 63 64 strStart = str(dateStart) + ' T00:00:00Z ' 65 strEnd = str(dateEnd) + ' T00:00:00Z ' 66 67 print ' Getting the upcoming 10 events ' 68 69 eventsResult = service.events().list( 70 calendarId = ' primary ' , 71 timeMin = strStart, 72 timeMax = strEnd, 73 singleEvents = True, 74 orderBy = ' startTime ' ).execute() 75 events = eventsResult.get( ' items ' , []) 76 77 if not events: 78 print ' No upcoming events found. ' 79 for event in events: 80 start = event[ ' start ' ].get( ' dateTime ' , event[ ' start ' ].get( ' date ' )) 81 print start, event[ ' summary ' ], event[ ' description ' ] if event.has_key( ' description ' ) else '' 82 83 if __name__ == ' __main__ ' : 84 main()