如何更新我的Python Google Sheet API凭据代码以避免包折旧?

时间:2017-11-15 14:10:27

标签: python authentication google-api google-oauth google-sheets-api

Google Sheets API Python Quickstart目前在其示例代码中使用deprecated packages,其中使用oauth2clienthttplib2而不是google-authgoogle-auth-oauthlib(或者google-auth?)已过时或即将成为。

如何重写此代码以最佳方式预测其当前状态并最终转移到google-auth等方式使用这些新库?特别是,在快速启动(下面)中是否有一个简单的重新实现,即检索,存储和使用凭证,使其更新?

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. ...

1 个答案:

答案 0 :(得分:2)

这个答案怎么样?我为Quickstart of Sheets 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也可能在不久的将来更新。

参考文献:

引用我参考准备此示例脚本如下。

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