import os from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from config.settings import settings class GSheetClient: SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] def __init__(self): self.creds = self._authenticate() def _authenticate(self): creds = None # The file token.json stores the user's access and refresh tokens if os.path.exists(settings.TOKEN_FILE): creds = Credentials.from_authorized_user_file(settings.TOKEN_FILE, self.SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: if not os.path.exists(settings.CREDENTIALS_FILE): raise FileNotFoundError(f"Credentials file not found at {settings.CREDENTIALS_FILE}. Please download it from Google Cloud Console.") flow = InstalledAppFlow.from_client_secrets_file( settings.CREDENTIALS_FILE, self.SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(settings.TOKEN_FILE, 'w') as token: token.write(creds.to_json()) return creds def fetch_data(self): try: service = build('sheets', 'v4', credentials=self.creds) sheet = service.spreadsheets() result = sheet.values().get( spreadsheetId=settings.SPREADSHEET_ID, range=settings.SHEET_RANGE ).execute() return result.get('values', []) except HttpError as err: print(f"An error occurred: {err}") return []