Spaces:
Sleeping
Sleeping
Download features/sheets_client.py from atlez/bittle-sneaker: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/spaces/atlez/bittle-sneaker/resolve/main/features/sheets_client.py
- Command line
-
hf download hf://spaces/atlez/bittle-sneaker/features/sheets_client.py
-
curl -L -o sheets_client.py https://huggingface.co/spaces/atlez/bittle-sneaker/resolve/main/features/sheets_client.py
2.05 kB
| # sheets_client.py | |
| import json | |
| import os | |
| from pathlib import Path | |
| import gspread | |
| from google.oauth2.service_account import Credentials | |
| SCOPES = ["https://www.googleapis.com/auth/spreadsheets"] | |
| PROJECT_ROOT = Path(__file__).resolve().parent.parent | |
| def resolve_service_account_file(file_path: str) -> str: | |
| path = Path(file_path).expanduser() | |
| if path.is_absolute(): | |
| return str(path) | |
| return str(PROJECT_ROOT / path) | |
| def get_sheet(worksheet_name: str | None = None): | |
| """รองรับทั้งโหมดไฟล์ (local) และโหมด JSON string (GitHub Actions)""" | |
| json_str = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") | |
| file_path = os.getenv("GOOGLE_SERVICE_ACCOUNT_FILE") | |
| if json_str: # โหมด Actions | |
| info = json.loads(json_str) | |
| creds = Credentials.from_service_account_info(info, scopes=SCOPES) | |
| elif file_path: # โหมด local | |
| creds = Credentials.from_service_account_file( | |
| resolve_service_account_file(file_path), scopes=SCOPES | |
| ) | |
| else: | |
| raise RuntimeError( | |
| "ไม่พบ GOOGLE_SERVICE_ACCOUNT_JSON หรือ GOOGLE_SERVICE_ACCOUNT_FILE" | |
| ) | |
| client = gspread.authorize(creds) | |
| sheet_id = os.getenv("GOOGLE_SHEETS_ID") | |
| spreadsheet = client.open_by_key(sheet_id) | |
| worksheet_name = worksheet_name or os.getenv("GOOGLE_SHEETS_WORKSHEET") | |
| prefix = os.getenv("WORKSHEET_PREFIX", "") | |
| if worksheet_name: | |
| prefixed_name = f"{prefix}{worksheet_name}" | |
| try: | |
| return spreadsheet.worksheet(prefixed_name) | |
| except gspread.exceptions.WorksheetNotFound: | |
| return spreadsheet.add_worksheet(title=prefixed_name, rows=100, cols=20) | |
| if prefix: | |
| prefixed_name = f"{prefix}Products" | |
| try: | |
| return spreadsheet.worksheet(prefixed_name) | |
| except gspread.exceptions.WorksheetNotFound: | |
| return spreadsheet.add_worksheet(title=prefixed_name, rows=100, cols=20) | |
| return spreadsheet.sheet1 | |