Data_request / sheets_integration.py
Rathapoom's picture
Update sheets_integration.py
34da3fd verified
raw
history blame
2.88 kB
import os
import json
import gspread
from google.oauth2 import service_account
from datetime import datetime
class SheetsLogger:
def __init__(self):
self.gc = None
self.sheet = None
self.initialize_client()
def initialize_client(self):
"""Initialize Google Sheets client"""
try:
# Get credentials from environment variable
creds_json = os.getenv('GOOGLE_SHEETS_CREDS')
if not creds_json:
raise ValueError("Google Sheets credentials not found in environment")
# Parse credentials JSON
creds_dict = json.loads(creds_json)
# Create credentials object
credentials = service_account.Credentials.from_service_account_info(
creds_dict,
scopes=['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive']
)
# Initialize gspread client
self.gc = gspread.authorize(credentials)
# Open spreadsheet by ID (get this from your sheet's URL)
SHEET_ID = os.getenv('GOOGLE_SHEET_ID')
self.sheet = self.gc.open_by_key(SHEET_ID).sheet1
except Exception as e:
print(f"Error initializing Google Sheets client: {str(e)}")
self.gc = None
self.sheet = None
def log_request(self, request_data):
"""Log a request to Google Sheets"""
if not self.sheet:
print("Sheet not initialized")
return False
try:
# Prepare row data
row = [
datetime.now().strftime("%Y-%m-%d %H:%M:%S"), # Timestamp
request_data.get('name', ''),
request_data.get('employee_id', ''),
request_data.get('email', ''),
request_data.get('department', ''),
request_data.get('request_details', ''),
request_data.get('frequency', ''),
request_data.get('urgency', ''),
request_data.get('system_response', '')
]
# Append row to sheet
self.sheet.append_row(row)
return True
except Exception as e:
print(f"Error logging to sheet: {str(e)}")
return False
def get_all_requests(self):
"""Get all requests from the sheet"""
if not self.sheet:
return None
try:
# Get all records
records = self.sheet.get_all_records()
return records
except Exception as e:
print(f"Error getting records: {str(e)}")
return None