""" Google Sheets API 클라이언트 - 서비스 계정 인증 버전 """ import json import os from typing import Dict, List, Optional, Tuple from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.errors import HttpError class GoogleSheetsClient: """Google Sheets API 클라이언트 (서비스 계정 버전)""" def __init__(self, service_account_info: Dict, spreadsheet_id: str): """ Args: service_account_info: 서비스 계정 정보 딕셔너리 spreadsheet_id: Google Sheets 스프레드시트 ID """ self.spreadsheet_id = spreadsheet_id self.service = None # 서비스 계정 정보로 credentials 생성 self.credentials = service_account.Credentials.from_service_account_info( service_account_info, scopes=['https://www.googleapis.com/auth/spreadsheets'] ) # Google Sheets API 서비스 객체 생성 self._build_service() def _build_service(self): """Google Sheets API 서비스 객체 빌드""" try: self.service = build('sheets', 'v4', credentials=self.credentials) except Exception as e: raise Exception(f"Google Sheets 서비스 초기화 실패: {str(e)}") def get_sheet_data(self, sheet_name: str, range_notation: str = None) -> Tuple[bool, any]: """시트 데이터 조회""" try: if range_notation: range_param = f"{sheet_name}!{range_notation}" else: range_param = sheet_name result = self.service.spreadsheets().values().get( spreadsheetId=self.spreadsheet_id, range=range_param ).execute() values = result.get('values', []) return True, values except HttpError as e: return False, f"데이터 조회 실패: {e.error_details}" except Exception as e: return False, f"데이터 조회 중 오류: {str(e)}" def append_row(self, sheet_name: str, values: List[str]) -> Tuple[bool, str]: """시트에 새 행 추가""" try: body = { 'values': [values], 'majorDimension': 'ROWS' } result = self.service.spreadsheets().values().append( spreadsheetId=self.spreadsheet_id, range=f"{sheet_name}", valueInputOption='USER_ENTERED', insertDataOption='INSERT_ROWS', body=body ).execute() updated_cells = result.get('updates', {}).get('updatedCells', 0) return True, f"성공적으로 {updated_cells}개 셀이 추가되었습니다" except HttpError as e: return False, f"행 추가 실패: {e.error_details}" except Exception as e: return False, f"행 추가 중 오류: {str(e)}" def get_last_row_number(self, sheet_name: str) -> Tuple[bool, int]: """시트의 마지막 행 번호 조회""" try: success, data = self.get_sheet_data(sheet_name) if success: return True, len(data) else: return False, 0 except Exception as e: return False, 0 def add_image_url(self, sheet_name: str, image_url: str) -> Tuple[bool, str]: """이미지 URL을 시트에 추가""" try: # 마지막 행 번호 확인 success, last_row = self.get_last_row_number(sheet_name) # 새 행에 이미지 URL 추가 success, message = self.append_row(sheet_name, [image_url]) if success: new_row_number = last_row + 1 return True, f"행 {new_row_number}에 이미지 URL이 추가되었습니다: {image_url}" else: return False, message except Exception as e: return False, f"이미지 URL 추가 중 오류: {str(e)}" def create_sheets_client_from_service_account(service_account_info: Dict, spreadsheet_id: str) -> GoogleSheetsClient: """서비스 계정 정보로 Google Sheets 클라이언트 생성""" return GoogleSheetsClient(service_account_info, spreadsheet_id) def create_sheets_client_from_env(spreadsheet_id: str) -> Optional[GoogleSheetsClient]: """환경 변수에서 서비스 계정 정보를 읽어 클라이언트 생성""" # 환경 변수에서 서비스 계정 정보 읽기 service_account_json = os.getenv('GOOGLE_SERVICE_ACCOUNT_JSON') if service_account_json: try: service_account_info = json.loads(service_account_json) return GoogleSheetsClient(service_account_info, spreadsheet_id) except json.JSONDecodeError: raise Exception("GOOGLE_SERVICE_ACCOUNT_JSON 환경 변수가 올바른 JSON 형식이 아닙니다") # 또는 파일에서 읽기 service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE', 'service_account.json') if os.path.exists(service_account_file): with open(service_account_file, 'r') as f: service_account_info = json.load(f) return GoogleSheetsClient(service_account_info, spreadsheet_id) return None # 기본 서비스 계정 정보 (실제 Private Key가 필요함) DEFAULT_SERVICE_ACCOUNT_INFO = { "type": "service_account", "project_id": "marketing-automation-463304", "private_key_id": "dc8e23fa63789d7af4e5f3e947b6ef8dcaee0d67", "private_key": "", # 실제 Private Key 필요 "client_email": "img-upload@marketing-automation-463304.iam.gserviceaccount.com", "client_id": "115745495358423216505", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": f"https://www.googleapis.com/robot/v1/metadata/x509/img-upload%40marketing-automation-463304.iam.gserviceaccount.com" } # 테스트 코드 if __name__ == "__main__": # 테스트 설정 SPREADSHEET_ID = "1tB5rYhBGdReeSg3t-7oFXoq2h2WbejNfzCxiL1cQUxY" # 서비스 계정 정보 (실제 Private Key 필요) service_account_info = DEFAULT_SERVICE_ACCOUNT_INFO.copy() service_account_info["private_key"] = "YOUR_PRIVATE_KEY_HERE" # 실제 키로 교체 필요 try: # 클라이언트 생성 client = create_sheets_client_from_service_account(service_account_info, SPREADSHEET_ID) print("✅ Google Sheets 클라이언트 생성 성공") # 테스트 이미지 URL 추가 test_url = "https://example.com/test-image.jpg" success, message = client.add_image_url("Storyboard", test_url) if success: print(f"✅ 이미지 URL 추가 성공: {message}") else: print(f"❌ 이미지 URL 추가 실패: {message}") except Exception as e: print(f"❌ 오류 발생: {str(e)}")