gspread w/ OAuth2Client Service Account Key

∥☆過路亽.° 提交于 2019-11-29 18:12:42

Authorisation expires every 0.5/1 hour (I think it depends on which of the two available methods you use to connect).

I have a google sheet connected 24/7 that updates every 2 seconds. Almost always the reason for a bad read/write is an authorisation error but also Google API can throw a variety of errors at you too that normally resolve after a few seconds. Here's one of my functions to update a cell, but using your details for auth_for_worksheet. Every operation (update single cell, update a range, read a column of values) has some similar construct as a function, which always returns an authorised worksheet. It's probably not the most elegant solution but the sheet has been connected for 3 months fine with no downtime.

def auth_for_worksheet():
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
    gc = gspread.authorize(credentials)
    wks = gc.open('spreadsheet name')
    p1 = wks.worksheet('Printer One')
    return p1

def update_single_cell(worksheet, counter, message):
    """ No data to return, update a single cell in column B to reflect this """

    single_cell_updated = False
    while not single_cell_updated:
        try:
            cell_location = "B" + str(counter)
            worksheet.update_acell(cell_location, message)
            single_cell_updated = True
        except gspread.exceptions.HTTPError:
            logger.critical("Could not update single cell")
            time.sleep(10)
            worksheet = auth_for_worksheet()
    logger.info("Updated single cell")
    return worksheet

if __name__ == '__main__':

    # your code here, but now to update a single cell
    wksheet = update_single_cell(wksheet, x, "NOT FOUND")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!