Last active
March 22, 2024 11:20
-
-
Save kouk/e56cfde316abaf34fb2599f4d87c9f74 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
import gspread | |
from google.oauth2 import service_account | |
def get_gspread_client() -> gspread.Client: | |
scope = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"] | |
# see https://docs.gspread.org/en/latest/oauth2.html | |
credentials_path = os.environ.get('GOOGLE_SERVICE_ACCOUNT_CREDENTIALS', None) | |
if credentials_path: | |
# Authenticate using the service account credentials file | |
credentials = service_account.Credentials.from_service_account_file(credentials_path, scopes=scope) | |
return gspread.authorize(credentials) | |
# default app credentials stored in `~/.config/gspread/credentials.json` | |
authorized_user_file = gspread.auth.DEFAULT_AUTHORIZED_USER_FILENAME | |
exit_after_authorization = not authorized_user_file.exists() | |
gc = gspread.oauth(scopes=scope) | |
if exit_after_authorization: | |
print("Successfully authorized the client app via OAuth2!") | |
sys.exit(0) | |
return gc | |
gc = get_gspread_client() | |
sheet_url = "https://docs.google.com/spreadsheets/d/1_ridW28-bBFYdoEfcJU79eXf3qn5NxX_XveW19pI4C8" | |
spreadsheet = gc.open_by_url(sheet_url) | |
worksheet = spreadsheet.worksheets()[0] | |
header_row, *data_rows = worksheet.get_all_values() | |
print(f"header_row: {header_row}") | |
# read column titled 'my column' | |
for i, row in enumerate(data_rows): | |
print(f"row {i+2} is: {row}") | |
# update first column | |
try: | |
n = len(data_rows) | |
column = [[f"row {i}"] for i in range(n)] | |
worksheet.update(values=column, range_name=f"A2:A{n+1}") | |
except Exception as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage with OAuth: