Spaces:
Running
Running
Create google_utils.py
Browse files- google_utils.py +52 -0
google_utils.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from google.oauth2 import service_account
|
| 5 |
+
from googleapiclient.discovery import build
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
# Cấu hình Log
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
# File json key bạn đã upload lên (đảm bảo file này nằm cùng thư mục)
|
| 13 |
+
SERVICE_ACCOUNT_FILE = 'service_account.json'
|
| 14 |
+
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
|
| 15 |
+
|
| 16 |
+
class GoogleSheetClient:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
self.creds = None
|
| 19 |
+
self.service = None
|
| 20 |
+
self.connect()
|
| 21 |
+
|
| 22 |
+
def connect(self):
|
| 23 |
+
"""Kết nối đến Google Sheets API dùng Service Account"""
|
| 24 |
+
try:
|
| 25 |
+
if os.path.exists(SERVICE_ACCOUNT_FILE):
|
| 26 |
+
self.creds = service_account.Credentials.from_service_account_file(
|
| 27 |
+
SERVICE_ACCOUNT_FILE, scopes=SCOPES
|
| 28 |
+
)
|
| 29 |
+
self.service = build('sheets', 'v4', credentials=self.creds)
|
| 30 |
+
logger.info("✅ Google Sheets API: Kết nối thành công.")
|
| 31 |
+
else:
|
| 32 |
+
logger.warning(f"⚠️ Không tìm thấy {SERVICE_ACCOUNT_FILE}. Chức năng ghi Sheet sẽ bị tắt.")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
logger.error(f"❌ Lỗi kết nối Google Sheets: {e}")
|
| 35 |
+
|
| 36 |
+
def append_row(self, sheet_id, data_row, sheet_range="Sheet1!A1"):
|
| 37 |
+
"""Ghi dòng mới vào Sheet"""
|
| 38 |
+
if not self.service: return {"status": "skipped", "reason": "No service"}
|
| 39 |
+
try:
|
| 40 |
+
body = { "values": [data_row] }
|
| 41 |
+
result = self.service.spreadsheets().values().append(
|
| 42 |
+
spreadsheetId=sheet_id, range=sheet_range,
|
| 43 |
+
valueInputOption="USER_ENTERED", insertDataOption="INSERT_ROWS",
|
| 44 |
+
body=body
|
| 45 |
+
).execute()
|
| 46 |
+
return {"status": "success"}
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logger.error(f"❌ Lỗi ghi Sheet: {e}")
|
| 49 |
+
return {"status": "error", "message": str(e)}
|
| 50 |
+
|
| 51 |
+
# Khởi tạo singleton
|
| 52 |
+
gsheet_client = GoogleSheetClient()
|