Data_request / sheets_integration.py
Rathapoom's picture
Create sheets_integration.py
4458876 verified
raw
history blame
1.94 kB
# sheets_integration.py
import os
import json
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import pandas as pd
class SheetsManager:
def __init__(self, credentials_path, spreadsheet_id):
self.credentials_path = credentials_path
self.spreadsheet_id = spreadsheet_id
self.credentials = None
self.service = None
self.initialize_service()
def initialize_service(self):
"""Initialize Google Sheets API service"""
self.credentials = service_account.Credentials.from_service_account_file(
self.credentials_path,
scopes=['https://www.googleapis.com/auth/spreadsheets']
)
self.service = build('sheets', 'v4', credentials=self.credentials)
def append_row(self, row_data):
"""Append a row to the spreadsheet"""
try:
body = {
'values': [list(row_data.values())]
}
result = self.service.spreadsheets().values().append(
spreadsheetId=self.spreadsheet_id,
range='Sheet1!A:I', # Adjust range as needed
valueInputOption='RAW',
body=body
).execute()
return True
except Exception as e:
print(f"Error appending to sheet: {str(e)}")
return False
def get_all_requests(self):
"""Get all requests from the spreadsheet"""
try:
result = self.service.spreadsheets().values().get(
spreadsheetId=self.spreadsheet_id,
range='Sheet1!A:I' # Adjust range as needed
).execute()
return pd.DataFrame(result.get('values', []))
except Exception as e:
print(f"Error reading sheet: {str(e)}")
return None