从Google日历获取Google日历条目

时间:2018-07-22 01:31:12

标签: python google-calendar-api

我正在尝试编写一个Python脚本,该脚本可让您从Google日历中提取条目。 我尝试通过以下示例使用Google Calendar API:https://developers.google.com/calendar/quickstart/python

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime

# Setup the Calendar API
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))

# 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'))
    print(start, event['summary'])

当我使用命令行“ python quickstart.py”运行它时,我得到了

 ModuleNotFoundError: No module named 'apiclient.discovery'

我尝试安装google api python客户端,但仍然无法正常工作。

pip install --upgrade google-api-python-client
conda install -c conda-forge google-api-python-client 

关于如何使用python提取Google日历条目还有其他建议吗?

2 个答案:

答案 0 :(得分:0)

要首先从Google获取日历和事件,您需要一个client_secret.json才能访问Google日历资源。

请勿使用oauth2client library,因为它已被弃用。而是使用google auth

您可以使用google auth oauthlib中的Flow或InstalledAppFlow来访问Google日历帐户资源。

from google_auth_oauthlib.flow import InstalledAppFlow

flow = InstalledAppFlow.from_client_secrets_file(
    'secret_file.json',
    scopes=['https://www.googleapis.com/auth/calendar']
)
credentials = flow.run_console()

将此凭据转储到文件中,因此您无需再次请求权限访问。

service = build(
    'calendar',
    'v3',
    credentials=credentials
)

通过此服务,您可以使用here中的所有Google日历API。

更新

由于我不使用oauth2client库,因此我手动转储了凭据:

with open('credentials.json', 'w') as f:
    f.write(json.dumps({
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes}))

答案 1 :(得分:0)

一个简单的解决方案是使用您日历的私有URL(在日历设置中列出),然后解析检索到的日历文件。无需OAuth即可运行。您将无法检索这些URL的列表,用户需要自己查找它们。