python gspread Google 表格保持连接活跃
我正在用 gspread
更新我的电子表格,这个过程大约需要一个小时,我有大约200个电子表格。似乎在更新大约30分钟后,连接就掉了。有没有办法保持登录状态?我以为我在保持连接活跃,因为我大约每30秒就会打开并写入不同的表格。
我可以使用 try
语句,如果连接断了就重新登录。我在想有没有人有更好的方法?
我习惯使用 gspread
的简单示例:
gc = gspread.login('thedude@abid.es', 'password')
sht1 = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')
我该如何将这个变成一个保持连接的登录,以便能够访问 sht1
?
1 个回答
4
为了保持连接活跃,你应该使用持久连接。
所以如果你查看主要文档:
http://burnash.github.io/gspread/#gspread.Client
你会看到 gspread.login
方法是 Client
的一个实例,而 Client
可以接受 http
头信息。
http://burnash.github.io/gspread/#gspread.httpsession.HTTPSession
现在在你的连接中添加这个头信息: Connection: Keep-Alive
import gspread
headers = gspread.httpsession.HTTPSession(headers={'Connection':'Keep-Alive'})
con = gspread.Client(auth=('you@gmail.com','password'),http_session=headers)
con.login()
con.open_by_key('....')
然后当你打印会话头信息时:
print con.session.headers
Out[5]: {'Authorization': u'GoogleLogin auth=xxxxxxx', 'Connection': 'Keep-Alive'}
关于持久连接的详细信息,可以查看这些链接:
http://en.wikipedia.org/wiki/HTTP_persistent_connection
http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html
关于 gspread httpsession
的代码细节,可以查看:
https://github.com/burnash/gspread/blob/master/gspread/httpsession.py