繁体   English   中英

写入Google表格时,python gspread连接超时

[英]python gspread connection time out when writing to google sheets

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

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()))

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

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

暂无
暂无

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

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