Is it possible to trigger events for google spreadsheet API V4 when we save new data on googlesheet?

24 views Asked by At

I am trying to fetch data from a google sheet using Google sheet API V4. Is it possible anyhow to know if someone has saved a data or made changes on the sheet? Based on that I want to make call to the api to get the data? More like I am trying to keep my mysql database synced with the google sheet. As soon as someone update the data, my database should get updated too. I am using Python. How do I do that?

Currently, I have created a function sync_data, that retrieves data from Google Sheets, compares it with existing data in the database, inserts new rows from the sheets into the database if they are not already present, and commits the changes, ensuring synchronization between the two data sources.

def sync_data(db_cursor, db_connection):
    credentials = Credentials.from_authorized_user_file("token.json", SCOPES)
    service = build("sheets", "v4", credentials=credentials)
    sheets = service.spreadsheets()

    # Fetch data from Google Sheets
    data_from_sheet = get_data_from_sheet(sheets)

    # Get all rows from the database
    db_cursor.execute("SELECT * FROM sheet_info")
    data_from_db = db_cursor.fetchall()

    # Get IDs of rows in the database
    db_ids = [row[0] for row in data_from_db]

    # Iterate over rows in the sheet
    for sheet_row in data_from_sheet:
        sheet_id = sheet_row[0]

        # If the sheet ID is not in the database, insert it
        if sheet_id not in db_ids:
            db_cursor.execute("""
                INSERT INTO sheet_info (id, Number1, Number2, Result, Stat)
                VALUES (%s, %s, %s, %s, %s)
            """, (sheet_id, sheet_row[1], sheet_row[2], sheet_row[3], 'Done'))

    # Commit changes to the database
    db_connection.commit()

    print("Synchronization completed.")

    db_connection.close()
0

There are 0 answers