【问题标题】:How to cache authorization for Google Sheets using gspread?如何使用 gspread 缓存 Google 表格的授权?
【发布时间】:2020-02-02 07:57:35
【问题描述】:

我正在尝试创建一个将一些数据发布到 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)

这非常有效,但不幸的是,这个过程非常缓慢。大部分时间似乎都用于授权。所以我的问题是:有没有办法授权和保存授权对象并将其重新用于接下来的几个请求?一旦有效期结束,该功能可以再次对其进行授权。非常感谢任何帮助!

【问题讨论】:

    标签: python google-sheets gspread


    【解决方案1】:
    • 您不想每次运行都运行授权进程。
    • 您希望将授权数据保存到文件中,并希望通过加载来使用 gspread。

    如果我的理解是正确的,那么这个答案呢?请认为这只是几个可能的答案之一。

    在这个答案中,包括访问令牌在内的令牌信息被保存为文件。因为 access token 的过期时间是 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秒,在脚本运行过程中可能会出现授权错误。

    参考:

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

    【讨论】:

    • 绝对惊人和详细。非常感谢!
    • @darkhorse 感谢您的回复。如果这有助于解决您的问题,我很高兴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多