-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook_server.py
More file actions
117 lines (94 loc) · 3.35 KB
/
Copy pathwebhook_server.py
File metadata and controls
117 lines (94 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
Flask Webhook Server for Google Sheets Integration
Google Sheets 변경사항을 받아서 DB에 저장하는 웹훅 서버
"""
from flask import Flask, request, jsonify
import sqlite3
import logging
from datetime import datetime
import json
# 로깅 설정
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# DB 경로
DB_PATH = '/home/user/webapp/master_codes.db'
def init_db():
"""데이터베이스 초기화"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS master_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sheet_data TEXT NOT NULL,
updated_at TEXT NOT NULL,
source TEXT DEFAULT 'google_sheets'
)
''')
conn.commit()
conn.close()
logger.info("Database initialized")
def save_master_code(sheet_data, source='webhook'):
"""마스터 코드를 DB에 저장"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# 기존 데이터 삭제 (최신 1개만 유지)
cursor.execute('DELETE FROM master_codes')
# 새 데이터 저장
updated_at = datetime.now().isoformat()
# sheet_data가 문자열이 아니면 JSON으로 변환
if isinstance(sheet_data, (list, dict)):
sheet_data = json.dumps(sheet_data, ensure_ascii=False)
cursor.execute(
'INSERT INTO master_codes (sheet_data, updated_at, source) VALUES (?, ?, ?)',
(sheet_data, updated_at, source)
)
conn.commit()
conn.close()
logger.info(f"Master code saved: {len(sheet_data)} bytes from {source}")
return updated_at
@app.route('/webhook', methods=['POST'])
def webhook():
"""
Google Apps Script에서 호출하는 웹훅 엔드포인트
Expected JSON payload:
{
"sheet_data": [...], // 전체 시트 데이터 (B~F열)
"timestamp": "2026-03-07T10:00:00", // 변경 시간 (선택사항)
"sheet_name": "상품 코드 최종(마스터 코드)" // 시트 이름 (선택사항)
}
"""
try:
data = request.get_json()
if not data:
return jsonify({'error': 'No JSON data provided'}), 400
logger.info(f"Webhook received: {len(str(data))} bytes")
# sheet_data 확인
if 'sheet_data' not in data:
return jsonify({'error': 'Missing sheet_data'}), 400
sheet_data = data['sheet_data']
# DB에 저장
updated_at = save_master_code(sheet_data, source='webhook')
logger.info(f"✅ Master code updated via webhook at {updated_at}")
return jsonify({
'status': 'success',
'message': 'Master code updated',
'updated_at': updated_at
}), 200
except Exception as e:
logger.error(f"Webhook error: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/health', methods=['GET'])
def health():
"""헬스체크 엔드포인트"""
return jsonify({
'status': 'ok',
'service': 'webhook_server'
}), 200
def run_server(port=5000):
"""Flask 서버 실행"""
init_db()
logger.info(f"Starting webhook server on port {port}")
app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
if __name__ == '__main__':
run_server()