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

gspread – Add Formula to Google Spreadsheet Cells

gspread documentation does not have any examples of adding formulas to the cells. If you try to use them with append_row or update_cell methods it records them as a string and not as a Formula.

You should instead use the update_cell method

Updating a Single Cell, considering you know the exact Row and Column Number

worksheet2.update_acell('A45','=SUM(D45:F45)')

Updating a Single Cell, considering you the exact Row and Column Number are not known

cell = worksheet2.find("David Letterman")
row_number = cell.row
workbook2_row='A'+str(row_number)

worksheet2.update_acell(workbook2_row,'=INDIRECT(CONCATENATE("D",ROW()))-INDIRECT(CONCATENATE("E",ROW()))')