如何更新我的Python Google Sheet API凭证代码以避免包贬值



Google Sheets API Python Quickstart目前在其示例代码中使用了不推荐使用的包,其中使用oauth2clienthttplib2而不是google-authgoogle-auth-oauthlib(或者google-auth?)已经过时或即将过时

如何重写此代码以使用这些新库,从而最好地预测它们的当前状态以及最终迁移到google-auth等。?特别是,在quickstart(下面)中,是否有一个简单的凭据检索、存储和使用的重新实现,使其更新?


from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl =  'https://sheets.googleapis.com/$discovery/rest?version=v4'
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
# etc. ...

这个答案怎么样?我为Sheetsneneneba API的快速启动准备了示例脚本。

  • 在这个样本中,它假设如下。
    • 表API已启用
    • 你有一个client_secret.json
  • 在本示例中,首先使用授权代码检索刷新令牌。刷新令牌保存到sheets.googleapis.com-python-quickstart.json。第一次运行后,访问令牌由刷新令牌检索
  • 在此示例中,从电子表格中检索单元格值

示例脚本:

import copy
import json
import os
import pprint
import google.oauth2.credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
pp = pprint.PrettyPrinter(indent=2)
CLIENT_SECRETS_FILE = "client_secret.json"
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'

def get_authenticated_service():
credential_path = os.path.join("./", 'sheets.googleapis.com-python-quickstart.json')
if os.path.exists(credential_path):
with open(credential_path, 'r') as f:
credential_params = json.load(f)
credentials = google.oauth2.credentials.Credentials(
credential_params["access_token"],
refresh_token=credential_params["refresh_token"],
token_uri=credential_params["token_uri"],
client_id=credential_params["client_id"],
client_secret=credential_params["client_secret"]
)
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_console()
with open(credential_path, 'w') as f:
p = copy.deepcopy(vars(credentials))
del p["expiry"]
json.dump(p, f, indent=4)
return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def spreadsheets_get(service):
spreadsheetId = "### spreadsheet ID ###"
rangeName = "Sheet1!a1:a10"
results = service.spreadsheets().get(
spreadsheetId=spreadsheetId,
ranges=rangeName
).execute()
pp.pprint(results)

if __name__ == '__main__':
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
service = get_authenticated_service()
spreadsheets_get(service)

注:

  • 为了保存credentials,需要使用oauth2client.file。因此,我在不使用oauth2client.file的情况下准备了示例脚本。如果您想使用oauth2client.file,请对其进行修改
  • 我认为Quickstart for Sheets API也可能在不久的将来更新

参考文献:

我为准备这个示例脚本而引用的参考文献如下。

  • 为已安装的应用程序使用OAuth 2.0
    • 有一个python的示例脚本
  • 用户指南
  • google.oauth2.credentials模块
  • 将OAuth 2.0用于Web服务器应用程序

如果我误解了你的问题,我很抱歉。

最新更新