簡體   English   中英

如何使用 gspread 緩存 Google 表格的授權?

[英]How to cache authorization for Google Sheets using gspread?

我正在嘗試創建一個簡單的函數,將一些數據發布到 Google Sheets 電子表格。 我在 AWS Lambda 中托管此函數。 無論如何,代碼看起來有點像這樣:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'my_creds.json', scope
)
gc = gspread.authorize(credentials)

這很完美,但不幸的是,這個過程非常緩慢。 大部分時間似乎都用於授權。 所以我的問題是:有什么方法可以授權和保存授權對象並在接下來的幾個請求中重新使用它? 一旦有效期用完,該函數可以再次對其進行授權。 任何幫助是極大的贊賞!

  • 您不想每次運行都運行授權過程。
  • 您想將授權數據保存到一個文件中,並希望通過加載它來使用 gspread。

如果我的理解是正確的,這個答案怎么樣? 請將此視為幾種可能的答案之一。

在這個答案中,包括訪問令牌的令牌信息被保存為文件。 因為訪問令牌的過期時間是 3600 秒。 這是使用的。

流動:

這個回答的流程如下。

  1. 檢查包含授權數據的令牌文件。
    • 如果該文件不存在,則授權過程會檢索訪問令牌並將令牌信息保存到令牌文件中。
    • 如果文件存在且限制時間大於當前時間,則使用從令牌文件中檢索到的訪問令牌。
    • 如果文件存在且限制時間小於當前時間,則授權過程檢索訪問令牌並將令牌信息保存到令牌文件中。
  2. 使用訪問令牌使用 gspread。

通過此流程,授權過程每大約 1 小時運行一次,而不是每次運行一次。

示例腳本:

在運行腳本之前,請修改token_filecredential_file的變量。

import datetime
import gspread
import json
import os
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.client import AccessTokenCredentials


token_file = "./access_token.txt"  # token file including the authorization data
credential_file = "###credential file of service account###"
now = int(datetime.datetime.now().timestamp())


def getNewAccessToken():
    scope = ['https://www.googleapis.com/auth/spreadsheets']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(credential_file, scope)
    gc = gspread.authorize(credentials)
    token_response = gc.auth.token_response
    token_response['limitTime'] = token_response['expires_in'] + now - 300
    with open(token_file, mode='w') as f:
        json.dump(token_response, f)
    return token_response['access_token']


def getCredential():
    access_token = ""
    if os.path.exists(token_file):
        with open(token_file) as f:
            token = json.load(f)
        access_token = token['access_token'] if token['limitTime'] > now else getNewAccessToken()
    else:
        access_token = getNewAccessToken()
    return AccessTokenCredentials(access_token, None)


# Use gspread
credentials = getCredential()
gc = gspread.authorize(credentials)
  • 在上面的腳本中,訪問令牌的限制時間設置為3600 - 300秒。 因為如果限制時間設置為3600秒,腳本運行過程中可能會出現授權錯誤。

參考:

如果我誤解了您的問題並且這不是您想要的方向,我深表歉意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM