几年前我创建了一个小的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。在我的电脑上工作的片段(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)
我没有对此进行过有力的测试,但它适用于使用我的个人帐户测试代码段。我确信可以和/或应该对企业应用程序进行更改,例如传递auth'd Http()
实例,检测范围更改等等。
您可以查看my GitHub repo上的完整代码:
要求:
我使用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)