flight / sheets_client.py
sonuprasad23's picture
Error Fixing
6cab6c6
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
import json
from datetime import datetime
SCOPE = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file"
]
def get_sheet():
try:
# Read the credentials from the environment variable (Hugging Face Secret)
creds_json_str = os.getenv("GOOGLE_CREDENTIALS_JSON")
if not creds_json_str:
print("Error: GOOGLE_CREDENTIALS_JSON secret is not set in Hugging Face.")
return None
creds_dict = json.loads(creds_json_str)
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, SCOPE)
client = gspread.authorize(creds)
sheet_id = os.getenv("GOOGLE_SHEET_ID")
if not sheet_id:
print("Error: GOOGLE_SHEET_ID secret is not set.")
return None
sheet = client.open_by_key(sheet_id).sheet1
return sheet
except Exception as e:
print(f"Error connecting to Google Sheets: {e}")
return None
def add_subscriber_to_sheet(email: str, fav_destinations: list, origin: str, dob: str):
sheet = get_sheet()
if sheet is None:
return False, "Could not connect to the subscribers sheet."
try:
all_values = sheet.get_all_values()
if not all_values or all_values[0] != ["timestamp", "email", "favorite_destinations", "usual_origin", "dob"]:
sheet.insert_row(["timestamp", "email", "favorite_destinations", "usual_origin", "dob"], 1)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
destinations_str = ", ".join(fav_destinations)
email_list = sheet.col_values(2)
if email in email_list:
return False, "This email is already subscribed."
sheet.append_row([timestamp, email, destinations_str, origin, dob])
return True, "Successfully subscribed!"
except Exception as e:
return False, f"An error occurred: {e}"