1

这是我现有的连接代码,可以正常工作

json_key = json.load(open('path/to/json.js')) 
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)

但大约 10 分钟后,我的连接将超时。

在阅读了一下之后,我发现在连接代码中使用了这个,

headers = gspread.httpsession.HTTPSession(headers={'Connection':'Keep-Alive'})

但我不确定如何包含到我现有的连接代码中。包含它的正确方法是什么?我看到的示例与我上面的连接代码不同,示例指定的密码不在我正在使用的 json 连接文件中

这是错误的输出。有时它们略有不同。但这一切都归结为相同的连接超时

File "/usr/local/lib/python2.7/dist-packages/gspread/models.py", line 429, in update_acell
return self.update_cell(*(self.get_int_addr(label)), val=val)
File "/usr/local/lib/python2.7/dist-packages/gspread/models.py", line 440, in update_cell
self._cell_addr(row, col))
File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 271, in get_cells_cell_id_feed
r = self.session.get(url)
File "/usr/local/lib/python2.7/dist-packages/gspread/httpsession.py", line 79, in get
return self.request('GET', url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gspread/httpsession.py", line 75, in request
raise HTTPError("%s: %s" % (response.status, response.read()))
4

1 回答 1

-1

如果超过时间,您可以调用函数重新连接到数据库。我提供了一个示例代码片段,您可以将其合并到您的程序中。

import gspread
from oauth2client.service_account import ServiceAccountCredentials

from datetime import datetime
from datetime import timedelta

def connect_database():

    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
    creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
    client = gspread.authorize(creds)

    workbook1 = client.open("File_Name")
    w1 = workbook1.worksheet("Sheet1")
    w2 = workbook1.worksheet("Sheet2")

    return w1,w2

program_start_time=datetime.now()

if datetime.now() > program_start_time + timedelta(minutes=10):
    worksheet1, worksheet2 = connect_database()
    program_start_time = datetime.now()   #Resets the Program Start Time

于 2019-04-12T09:34:10.410 回答