-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsheets_client.py
More file actions
126 lines (102 loc) · 4.37 KB
/
sheets_client.py
File metadata and controls
126 lines (102 loc) · 4.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
"""
Google Sheets Client - Abstracted sheet access functionality.
"""
from typing import Optional, List
import gspread
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os.path
# Scopes for Google Sheets API
SCOPES = [
'https://www.googleapis.com/auth/spreadsheets.readonly'
]
# Token file to store user credentials
TOKEN_FILE = "token.pickle"
CREDENTIALS_FILE = "credentials.json"
class GoogleSheetsClient:
"""Handles Google Sheets authentication and access."""
def __init__(self, credentials_path: str = CREDENTIALS_FILE):
"""
Initialize the Google Sheets client.
Args:
credentials_path: Path to the OAuth2 client credentials JSON file
"""
self.credentials_path = credentials_path
self.client: Optional[gspread.Client] = None
self._authenticated = False
def authenticate(self) -> None:
"""
Authenticate with Google Sheets API using OAuth2 flow.
Opens browser for user to login with Google account.
"""
creds: Optional[Credentials] = None
# Check if we have saved credentials
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE, 'rb') as token:
creds = pickle.load(token)
# If no valid credentials, let user log in
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
print("Refreshing expired credentials...")
creds.refresh(Request())
else:
if not os.path.exists(self.credentials_path):
raise FileNotFoundError(
f"Credentials file not found: {self.credentials_path}\n"
"Please download OAuth2 credentials from Google Cloud Console:\n"
"1. Go to https://console.cloud.google.com/\n"
"2. Enable Google Sheets API\n"
"3. Create OAuth2 credentials (Desktop app)\n"
"4. Download as 'credentials.json'"
)
print("Opening browser for Google login...")
flow = InstalledAppFlow.from_client_secrets_file(
self.credentials_path, SCOPES
)
creds = flow.run_local_server(port=0)
# Save credentials for future use
with open(TOKEN_FILE, 'wb') as token:
pickle.dump(creds, token)
self.client = gspread.authorize(creds)
self._authenticated = True
@property
def is_authenticated(self) -> bool:
"""Check if the client is authenticated."""
return self._authenticated and self.client is not None
def open_spreadsheet(self, spreadsheet_id: str) -> gspread.Spreadsheet:
"""
Open a spreadsheet by its ID.
Args:
spreadsheet_id: The Google Sheets spreadsheet ID
Returns:
gspread.Spreadsheet object
"""
if not self.is_authenticated:
raise RuntimeError("Must authenticate before accessing spreadsheets")
return self.client.open_by_key(spreadsheet_id)
def get_worksheet_data(self, spreadsheet_id: str, sheet_name: str) -> List[List[str]]:
"""
Get all data from a specific worksheet.
Args:
spreadsheet_id: The Google Sheets spreadsheet ID
sheet_name: The name of the worksheet
Returns:
List of rows, where each row is a list of cell values
"""
spreadsheet = self.open_spreadsheet(spreadsheet_id)
worksheet = spreadsheet.worksheet(sheet_name)
return worksheet.get_all_values()
def get_first_worksheet_data(self, spreadsheet_id: str) -> List[List[str]]:
"""
Get all data from the first worksheet in a spreadsheet.
Args:
spreadsheet_id: The Google Sheets spreadsheet ID
Returns:
List of rows, where each row is a list of cell values
"""
spreadsheet = self.open_spreadsheet(spreadsheet_id)
worksheet = spreadsheet.get_worksheet(0)
return worksheet.get_all_values()