如何确定令牌到期时间(Python)

2024-06-16 10:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找一个方法来确定Oauth2令牌上剩余的时间量。我确定只有在令牌过期后刷新令牌才有效(因此我不能任意刷新令牌)。这给我留下了一个问题,因为我计划收集数据,然后在for循环中,将多行写入google工作表。在

我担心的是我的代币将在写入谷歌工作表期间过期。除非我能预测代币什么时候到期,否则我就有两个难看的选择:

跟踪代币时间

对写入的每一行使用Try/exception。在

我的测试/学习代码如下。在

如有任何推荐信,将不胜感激。在

谢谢 乔恩

#!/usr/bin/python3
# -- developed with Python 3.4.2
#
# External Resources __________________________________________________________
import time
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import traceback

# Initialize gspread credentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('MyjsonFile.json',scope)
headers = gspread.httpsession.HTTPSession(headers={'Connection': 'Keep-Alive'})
client = gspread.Client(auth=credentials, http_session=headers)
client.login()
workbook = client.open("DataLogger")
wksheet = workbook.get_worksheet(1)

# Start loop ________________________________________________________________
samplecount = 1
while True:
    data_time = (time.strftime("%Y-%m-%d %H:%M:%S"))
    row_data = [samplecount,data_time]
    if credentials.access_token_expired:
        client.login()        
    wksheet.append_row(row_data)
    print("Number of rows in out worksheet  ",wksheet.row_count)
    print ("samplecount  ", samplecount, row_data)  
    print()
    samplecount += 1
    time.sleep(16*60)

Tags: importclientjsondatatimegoogle时间headers