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

时间:2018-08-29 19:46:20

标签: python google-api google-oauth google-api-python-client oauth2client

几年前,我创建了一个小型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)

2 个答案:

答案 0 :(得分:5)

根据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)

答案 1 :(得分:2)

我还没有对它进行严格的测试,但是它可以用我的个人帐户测试代码段。我确定企业应用程序可能会和/或应该对此进行更改,例如传递经过身份验证的Http()实例,检测范围更改等。

您可以在my GitHub repo上查看完整的代码:

要求:

  • google-api-python-client
  • google-auth
  • google-auth-oauthlib
  • 任何采用上述方法的人

我使用InstalledAppFlow类,并且通常遵循Google's Python auth guide上的说明。

代码(Python 3.6)

# Google API imports
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['your scopes', 'here']

def get_saved_credentials(filename='creds.json'):
    '''Read in any saved OAuth data/tokens
    '''
    fileData = {}
    try:
        with open(filename, 'r') as file:
            fileData: dict = json.load(file)
    except FileNotFoundError:
        return None
    if fileData and 'refresh_token' in fileData and 'client_id' in fileData and 'client_secret' in fileData:
        return Credentials(**fileData)
    return None

def store_creds(credentials, filename='creds.json'):
    if not isinstance(credentials, Credentials):
        return
    fileData = {'refresh_token': credentials.refresh_token,
                'token': credentials.token,
                'client_id': credentials.client_id,
                'client_secret': credentials.client_secret,
                'token_uri': credentials.token_uri}
    with open(filename, 'w') as file:
        json.dump(fileData, file)
    print(f'Credentials serialized to {filename}.')

def get_credentials_via_oauth(filename='client_secret.json', scopes=SCOPES, saveData=True) -> Credentials:
    '''Use data in the given filename to get oauth data
    '''
    iaflow: InstalledAppFlow = InstalledAppFlow.from_client_secrets_file(filename, scopes)
    iaflow.run_local_server()
    if saveData:
        store_creds(iaflow.credentials)
    return iaflow.credentials

def get_service(credentials, service='sheets', version='v4'):
    return build(service, version, credentials=credentials)

当时的用法是

creds = get_saved_credentials()
if not creds:
    creds = get_credentials_via_oauth()
sheets = get_service(creds)