Search code examples
pythongspread

python gspread google spreadsheet keeping connection alive


I'm updating my spreadsheets using gspread, the process takes about an hour, i have about 200 spreadsheets. It seems about 30 minutes into the updating the sheets, the connection drops. Is there a way to keep the login alive? I thought I was keeping the connection alive because I'm opening and writing to different sheets about every 30 seconds.

I can use a try statement and if it bombs re-login. I was wondering if anybody had a better way?

I'm used to using the simple example from gspread example of:

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

How do I turn this into a keep alive connection login to arrive at sht1?


Solution

  • For keeping alive connection you should use persistent connection.

    So if you check main document:

    http://burnash.github.io/gspread/#gspread.Client

    You will see the gspread.login method is instance of Client. and Client can accept http headers.

    http://burnash.github.io/gspread/#gspread.httpsession.HTTPSession

    Now add this header in your connection : 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('....')
    

    Then when you get print of session headers:

    print con.session.headers
    Out[5]: {'Authorization': u'GoogleLogin auth=xxxxxxx', 'Connection': 'Keep-Alive'}
    

    For persistent connection details have a look into these links:

    http://en.wikipedia.org/wiki/HTTP_persistent_connection

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html

    For codes details of gspread httpsession have a look into:

    https://github.com/burnash/gspread/blob/master/gspread/httpsession.py