如何在Python中使用google.auth而不是oauth2client来访问我的Google日历

几年前我创建了一个小的
Python程序,它能够使用oauth2client维护我的日历,现在已经弃用并用google.auth取代 – 但我找不到任何有用的文档,我的程序停止工作抱怨_module KeyError没有人看来除了通过升级解决了.

我无法弄清楚如何用google.auth替换oauth2client:

import datetime
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)

最佳答案 根据
oauth2client deprecation notes,用于管理Google用户凭据的替代品是
google-auth-oauthlib.在我的PC上工作的片段(python 3.6)下方.

由于文档突出显示新库不保存凭据,这就是我使用pickle保存它们的原因.也许,根据您的应用程序要求,您希望拥有更强大的解决方案(如数据库).

import os
import pickle

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/calendar.readonly', ]


# we check if the file to store the credentials exists
if not os.path.exists('credentials.dat'):

    flow = InstalledAppFlow.from_client_secrets_file('client_id.json', SCOPES)
    credentials = flow.run_local_server()

    with open('credentials.dat', 'wb') as credentials_dat:
        pickle.dump(credentials, credentials_dat)
else:
    with open('credentials.dat', 'rb') as credentials_dat:
        credentials = pickle.load(credentials_dat)

if credentials.expired:
    credentials.refresh(Request())

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

calendars_get_params = {
        'calendarId': 'primary',
    }

test = calendar_sdk.calendars().get(**calendars_get_params).execute()
print(test)
点赞