【问题标题】:python gspread google spreadsheet keeping connection alivepython gspread google电子表格保持连接活跃
【发布时间】:2014-05-09 15:50:05
【问题描述】:

我正在使用gspread 更新我的电子表格,这个过程大约需要一个小时,我有大约 200 个电子表格。似乎在更新工作表大约 30 分钟后,连接断开了。有没有办法让登录保持活跃?我以为我保持了连接,因为我大约每 30 秒打开并写入不同的工作表。

我可以使用try 语句,如果它炸弹重新登录。我想知道是否有人有更好的方法?

我习惯使用来自gspread 的简单示例:

gc = gspread.login('thedude@abid.es', 'password')
sht1 = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')

如何将其转换为保持连接登录以到达sht1

【问题讨论】:

    标签: python gspread


    【解决方案1】:

    为了保持连接,你应该使用持久连接。

    所以如果你检查主文档:

    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

    【讨论】:

    • 你能给我看几行代码吗?我如何使用持久连接登录?看了链接还是没看懂。我确实尝试过挖掘代码。
    • @jason_cant_code 确定!我更新了我的帖子。检查它;)
    • 即使在将连接设置为持久连接之后,Google 也会在足够的时间后返回一条错误的服务线路。尝试使用 con.login() 重新登录并不能解决问题。重新启动脚本会持续一两分钟...
    • Google 不再支持这种身份验证方法。看到这个链接developers.google.com/identity/protocols/OAuth2
    • 试试这个代码:import gspread; from oauth2client.service_account import ServiceAccountCredentials; scope = ['https://spreadsheets.google.com/feeds']; credentials = ServiceAccountCredentials.from_json_keyfile_name('Pluss Inventory-7160481b4bc0.json', scope); headers = gspread.httpsession.HTTPSession(headers={'Connection': 'Keep-Alive'}); gc = gspread.Client(auth=credentials, http_session=headers); gc.login()
    猜你喜欢
    • 2011-05-21
    • 2011-08-07
    • 1970-01-01
    • 2020-12-06
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多