【问题标题】:Fetch Google Calendar Entries from Google Calendar从 Google 日历中获取 Google 日历条目
【发布时间】:2018-07-22 01:31:11
【问题描述】:

我正在尝试编写一个允许您从谷歌日历中获取条目的 python 脚本。 我尝试在此处使用 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 获取谷歌日历条目还有其他建议吗?

【问题讨论】:

  • python2 还是 python3?假设 pip 确实做了什么,它在哪里安装了文件?

标签: python google-calendar-api


【解决方案1】:

要首先从 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 的所有谷歌日历 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}))

【讨论】:

  • @PandaPanda 我只是转储到一个 credentials.json 文件中,查看我更新的答案以查看 json 转储格式。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多