gspread timeout – Reconnecting to the Google API

gspread loses connection with the Google API probably every 10 minutes. This can be easily tackled by calling a function or Class which reconnects to the database.

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s