我正在尝试创建一个简单的函数,将一些数据发布到 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。
如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。
在此答案中,包括访问令牌的令牌信息被保存为文件。因为access token的过期时间是3600秒。这是用的。
Flow:
这个答案的流程如下。
- Check the token file including the authorization data.
- 如果该文件不存在,则授权过程将检索访问令牌并将令牌信息保存到令牌文件中。
- 如果文件存在并且限制时间超过当前时间,则使用从令牌文件检索的访问令牌。
- 如果该文件存在并且限制时间小于当前时间,则授权进程检索访问令牌并将令牌信息保存到令牌文件中。
- 使用访问令牌来使用 gspread。
通过此流程,授权过程大约每 1 小时运行一次,而不是每次运行。
示例脚本:
运行脚本之前,请修改以下变量token_file
and 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
秒,脚本运行过程中可能会出现授权错误。
参考:
- oauth2client.client.AccessTokenCredentials https://oauth2client.readthedocs.io/en/latest/source/oauth2client.client.html#oauth2client.client.AccessTokenCredentials
如果我误解了你的问题并且这不是你想要的方向,我深表歉意。
更新于 2023 年 2 月 16 日
现阶段好像gspread用的是google-auth
。这样,当使用当前的 gspread 运行该脚本时,就会发生错误。因此,我将更新的脚本发布到这个线程 https://stackoverflow.com/q/75420947。如果您想使用当前的 gspread 来使用此方法,请检查该线程。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)