[英]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)
這很完美,但不幸的是,這個過程非常緩慢。 大部分時間似乎都用於授權。 所以我的問題是:有什么方法可以授權和保存授權對象並在接下來的幾個請求中重新使用它? 一旦有效期用完,該函數可以再次對其進行授權。 任何幫助是極大的贊賞!
如果我的理解是正確的,這個答案怎么樣? 請將此視為幾種可能的答案之一。
在這個答案中,包括訪問令牌的令牌信息被保存為文件。 因為訪問令牌的過期時間是 3600 秒。 這是使用的。
這個回答的流程如下。
通過此流程,授權過程每大約 1 小時運行一次,而不是每次運行一次。
在運行腳本之前,請修改token_file
和credential_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.