简体   繁体   English

如何使用 gspread 缓存 Google 表格的授权?

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

I am trying to create a simple function that posts some data to a Google Sheets spreadsheet.我正在尝试创建一个简单的函数,将一些数据发布到 Google Sheets 电子表格。 I am hosting this function in AWS Lambda.我在 AWS Lambda 中托管此函数。 Anyway, the code looks kinda like this:无论如何,代码看起来有点像这样:

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)

This works perfectly, but unfortunately, the process is pretty slow.这很完美,但不幸的是,这个过程非常缓慢。 The bulk of the time it seems is taken to authorize.大部分时间似乎都用于授权。 So my question is this: is there some way to authorize and save the authorization object and re-use it for the next few requests?所以我的问题是:有什么方法可以授权和保存授权对象并在接下来的几个请求中重新使用它? Once the validity runs out, the function can authorize it again.一旦有效期用完,该函数可以再次对其进行授权。 Any help is greatly appreciated!任何帮助是极大的赞赏!

  • You don't want to run the authorize process every run.您不想每次运行都运行授权过程。
  • You want to save the authorization data to a file and want to use gspread by loading it.您想将授权数据保存到一个文件中,并希望通过加载它来使用 gspread。

If my understanding is correct, how about this answer?如果我的理解是正确的,这个答案怎么样? Please think of this as just one of several possible answers.请将此视为几种可能的答案之一。

In this answer, the token information including the access token are saved as a file.在这个答案中,包括访问令牌的令牌信息被保存为文件。 Because the expiration time of access token is 3600 seconds.因为访问令牌的过期时间是 3600 秒。 This is used.这是使用的。

Flow:流动:

The flow of this answer is as follows.这个回答的流程如下。

  1. Check the token file including the authorization data.检查包含授权数据的令牌文件。
    • If the file is NOT existing, the access token is retrieved by the authorization process and save the token information to the token file.如果该文件不存在,则授权过程会检索访问令牌并将令牌信息保存到令牌文件中。
    • If the file is existing and the limitation time is more than the current time, the access token retrieved from the token file is used.如果文件存在且限制时间大于当前时间,则使用从令牌文件中检索到的访问令牌。
    • If the file is existing and the limitation time is less than the current time, the access token is retrieved by the authorization process and save the token information to the token file.如果文件存在且限制时间小于当前时间,则授权过程检索访问令牌并将令牌信息保存到令牌文件中。
  2. Use gspread using the access token.使用访问令牌使用 gspread。

By this flow, the authorization process is run every about 1 hour instead of every run.通过此流程,授权过程每大约 1 小时运行一次,而不是每次运行一次。

Sample script:示例脚本:

Before you run the script, please modify the variables of token_file and credential_file .在运行脚本之前,请修改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)
  • In above script, the limitation time of the access token is set as 3600 - 300 seconds.在上面的脚本中,访问令牌的限制时间设置为3600 - 300秒。 Because if the limitation time is set as 3600 seconds, an error of authorization might occur during the script is running.因为如果限制时间设置为3600秒,脚本运行过程中可能会出现授权错误。

Reference:参考:

If I misunderstood your question and this was not the direction you want, I apologize.如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM