gpt4 book ai didi

python - 如何使用 gspread 缓存 Google Sheets 的授权?

转载 作者:行者123 更新时间:2023-12-01 06:28:18 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的函数,将一些数据发布到 Google 表格电子表格中。我在 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。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。

在此答案中,包括访问 token 在内的 token 信息将保存为文件。因为access token的过期时间是3600秒。这是用的。

流程:

这个答案的流程如下。

  1. 检查包含授权数据的 token 文件。
    • 如果该文件不存在,授权过程将检索访问 token 并将 token 信息保存到 token 文件中。
    • 如果文件存在且限制时间超过当前时间,则使用从 token 文件中检索到的访问 token 。
    • 如果文件存在且限制时间小于当前时间,则授权进程会检索访问 token 并将 token 信息保存到 token 文件中。
  2. 使用访问 token 来使用 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)
  • 在上面的脚本中,访问 token 的限制时间设置为3600 - 300秒。因为如果限制时间设置为3600秒,脚本运行过程中可能会出现授权错误。

引用:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

更新于 2023 年 2 月 16 日

现阶段,gspread似乎使用了google-auth。这样,当使用当前的 gspread 运行该脚本时,就会发生错误。因此,我将更新后的脚本发布到 this thread 。如果您想使用当前的 gspread 来使用此方法,请检查该线程。

关于python - 如何使用 gspread 缓存 Google Sheets 的授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com