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 = ['', '']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

workbook1 ="File_Name")
w1 = workbook1.worksheet("Sheet1")
w2 = workbook1.worksheet("Sheet2")

return w1,w2

if > program_start_time + timedelta(minutes=10):
worksheet1, worksheet2 = connect_database()
program_start_time = #Resets the Program Start Time