구글드라이브 연동 로그 추가
This commit is contained in:
23
app.py
23
app.py
@@ -1,11 +1,15 @@
|
|||||||
from flask import Flask, render_template, request, jsonify, session, redirect, url_for
|
from flask import Flask, render_template, request, jsonify, session, redirect, url_for
|
||||||
import os
|
import os
|
||||||
|
import logging
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from utils.word_processor import WordProcessor
|
from utils.word_processor import WordProcessor
|
||||||
from utils.google_drive import GoogleDriveUploader
|
from utils.google_drive import GoogleDriveUploader
|
||||||
from config import Config
|
from config import Config
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config.from_object(Config)
|
app.config.from_object(Config)
|
||||||
|
|
||||||
@@ -29,17 +33,24 @@ drive_uploader = None
|
|||||||
try:
|
try:
|
||||||
# credentials.json 파일이 있는 경우에만 초기화 시도
|
# credentials.json 파일이 있는 경우에만 초기화 시도
|
||||||
if os.path.exists(app.config['GOOGLE_DRIVE_CREDENTIALS_FILE']):
|
if os.path.exists(app.config['GOOGLE_DRIVE_CREDENTIALS_FILE']):
|
||||||
|
logger.info(
|
||||||
|
"구글 드라이브 업로더 초기화 시도 | credentials=%s token=%s",
|
||||||
|
app.config['GOOGLE_DRIVE_CREDENTIALS_FILE'],
|
||||||
|
app.config['GOOGLE_DRIVE_TOKEN_FILE'],
|
||||||
|
)
|
||||||
drive_uploader = GoogleDriveUploader(
|
drive_uploader = GoogleDriveUploader(
|
||||||
app.config['GOOGLE_DRIVE_CREDENTIALS_FILE'],
|
app.config['GOOGLE_DRIVE_CREDENTIALS_FILE'],
|
||||||
app.config['GOOGLE_DRIVE_TOKEN_FILE']
|
app.config['GOOGLE_DRIVE_TOKEN_FILE']
|
||||||
)
|
)
|
||||||
|
logger.info("구글 드라이브 업로더 초기화 성공")
|
||||||
|
else:
|
||||||
|
logger.info("credentials.json이 없어 구글 드라이브 업로더를 초기화하지 않았습니다.")
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
# 인증 파일이 없으면 조용히 넘어감
|
logger.warning("구글 드라이브 인증 파일을 찾을 수 없습니다. 업로드 기능 비활성화.")
|
||||||
pass
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 브라우저 관련 오류나 기타 오류는 조용히 처리
|
# 브라우저 관련 오류나 기타 오류는 조용히 처리
|
||||||
# 서버 환경에서는 브라우저가 없을 수 있으므로 정상적인 상황
|
# 서버 환경에서는 브라우저가 없을 수 있으므로 정상적인 상황
|
||||||
pass
|
logger.warning("구글 드라이브 초기화 중 오류 발생: %s", str(e))
|
||||||
|
|
||||||
@app.route('/auth', methods=['GET', 'POST'])
|
@app.route('/auth', methods=['GET', 'POST'])
|
||||||
def auth():
|
def auth():
|
||||||
@@ -157,12 +168,15 @@ def step5():
|
|||||||
|
|
||||||
# 구글 드라이브 업로드
|
# 구글 드라이브 업로드
|
||||||
if drive_uploader and app.config['GOOGLE_DRIVE_FOLDER_ID']:
|
if drive_uploader and app.config['GOOGLE_DRIVE_FOLDER_ID']:
|
||||||
|
upload_filename = f"교리점검표_{all_data['basic_info'].get('name', '무명')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
|
||||||
|
logger.info("구글 드라이브 업로드 시도 | file=%s, folder=%s", upload_filename, app.config['GOOGLE_DRIVE_FOLDER_ID'])
|
||||||
try:
|
try:
|
||||||
file_id = drive_uploader.upload_file(
|
file_id = drive_uploader.upload_file(
|
||||||
output_path,
|
output_path,
|
||||||
f"교리점검표_{all_data['basic_info'].get('name', '무명')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx",
|
upload_filename,
|
||||||
app.config['GOOGLE_DRIVE_FOLDER_ID']
|
app.config['GOOGLE_DRIVE_FOLDER_ID']
|
||||||
)
|
)
|
||||||
|
logger.info("구글 드라이브 업로드 성공 | file_id=%s", file_id)
|
||||||
# 업로드 후 로컬 파일 삭제 (선택사항)
|
# 업로드 후 로컬 파일 삭제 (선택사항)
|
||||||
# os.remove(output_path)
|
# os.remove(output_path)
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@@ -171,6 +185,7 @@ def step5():
|
|||||||
'file_id': file_id
|
'file_id': file_id
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
logger.warning("구글 드라이브 업로드 실패: %s", str(e))
|
||||||
# 업로드 실패 시 로컬 파일 경로 반환
|
# 업로드 실패 시 로컬 파일 경로 반환
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'success': True,
|
'success': True,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import os
|
import os
|
||||||
|
import logging
|
||||||
from google.oauth2.credentials import Credentials
|
from google.oauth2.credentials import Credentials
|
||||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||||
from google.auth.transport.requests import Request
|
from google.auth.transport.requests import Request
|
||||||
@@ -7,6 +8,13 @@ from googleapiclient.http import MediaFileUpload
|
|||||||
import pickle
|
import pickle
|
||||||
|
|
||||||
SCOPES = ['https://www.googleapis.com/auth/drive.file']
|
SCOPES = ['https://www.googleapis.com/auth/drive.file']
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
if not logger.handlers:
|
||||||
|
handler = logging.StreamHandler()
|
||||||
|
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s - %(message)s')
|
||||||
|
handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(handler)
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
class GoogleDriveUploader:
|
class GoogleDriveUploader:
|
||||||
def __init__(self, credentials_file, token_file):
|
def __init__(self, credentials_file, token_file):
|
||||||
@@ -18,16 +26,20 @@ class GoogleDriveUploader:
|
|||||||
def _authenticate(self):
|
def _authenticate(self):
|
||||||
"""구글 드라이브 인증"""
|
"""구글 드라이브 인증"""
|
||||||
creds = None
|
creds = None
|
||||||
|
logger.info("구글 드라이브 인증 시작 | credentials=%s token=%s", self.credentials_file, self.token_file)
|
||||||
|
|
||||||
# 기존 토큰 파일이 있으면 로드
|
# 기존 토큰 파일이 있으면 로드
|
||||||
if os.path.exists(self.token_file):
|
if os.path.exists(self.token_file):
|
||||||
with open(self.token_file, 'rb') as token:
|
with open(self.token_file, 'rb') as token:
|
||||||
creds = pickle.load(token)
|
creds = pickle.load(token)
|
||||||
|
logger.info("기존 토큰 파일 로드 성공")
|
||||||
|
|
||||||
# 유효한 인증 정보가 없으면 새로 인증
|
# 유효한 인증 정보가 없으면 새로 인증
|
||||||
if not creds or not creds.valid:
|
if not creds or not creds.valid:
|
||||||
if creds and creds.expired and creds.refresh_token:
|
if creds and creds.expired and creds.refresh_token:
|
||||||
|
logger.info("토큰 만료, refresh 시도")
|
||||||
creds.refresh(Request())
|
creds.refresh(Request())
|
||||||
|
logger.info("토큰 refresh 성공")
|
||||||
else:
|
else:
|
||||||
if not os.path.exists(self.credentials_file):
|
if not os.path.exists(self.credentials_file):
|
||||||
raise FileNotFoundError(
|
raise FileNotFoundError(
|
||||||
@@ -39,7 +51,9 @@ class GoogleDriveUploader:
|
|||||||
self.credentials_file, SCOPES)
|
self.credentials_file, SCOPES)
|
||||||
# 서버 환경에서는 브라우저가 없을 수 있으므로 예외 처리
|
# 서버 환경에서는 브라우저가 없을 수 있으므로 예외 처리
|
||||||
try:
|
try:
|
||||||
|
logger.info("로컬 서버 플로우로 인증 시도")
|
||||||
creds = flow.run_local_server(port=0)
|
creds = flow.run_local_server(port=0)
|
||||||
|
logger.info("로컬 서버 플로우 인증 성공")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 브라우저를 열 수 없는 경우 (서버 환경 등)
|
# 브라우저를 열 수 없는 경우 (서버 환경 등)
|
||||||
# 토큰 파일이 이미 있다면 재시도하지 않고 예외 발생
|
# 토큰 파일이 이미 있다면 재시도하지 않고 예외 발생
|
||||||
@@ -51,8 +65,10 @@ class GoogleDriveUploader:
|
|||||||
# 토큰 저장
|
# 토큰 저장
|
||||||
with open(self.token_file, 'wb') as token:
|
with open(self.token_file, 'wb') as token:
|
||||||
pickle.dump(creds, token)
|
pickle.dump(creds, token)
|
||||||
|
logger.info("토큰 파일 저장 완료: %s", self.token_file)
|
||||||
|
|
||||||
self.service = build('drive', 'v3', credentials=creds)
|
self.service = build('drive', 'v3', credentials=creds)
|
||||||
|
logger.info("구글 드라이브 서비스 생성 완료")
|
||||||
|
|
||||||
def upload_file(self, file_path, file_name, folder_id=None):
|
def upload_file(self, file_path, file_name, folder_id=None):
|
||||||
"""파일을 구글 드라이브에 업로드"""
|
"""파일을 구글 드라이브에 업로드"""
|
||||||
@@ -63,6 +79,7 @@ class GoogleDriveUploader:
|
|||||||
if folder_id:
|
if folder_id:
|
||||||
file_metadata['parents'] = [folder_id]
|
file_metadata['parents'] = [folder_id]
|
||||||
|
|
||||||
|
logger.info("구글 드라이브 업로드 준비 | file=%s, name=%s, folder=%s", file_path, file_name, folder_id)
|
||||||
media = MediaFileUpload(file_path, mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
media = MediaFileUpload(file_path, mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
||||||
|
|
||||||
file = self.service.files().create(
|
file = self.service.files().create(
|
||||||
@@ -71,5 +88,7 @@ class GoogleDriveUploader:
|
|||||||
fields='id'
|
fields='id'
|
||||||
).execute()
|
).execute()
|
||||||
|
|
||||||
return file.get('id')
|
file_id = file.get('id')
|
||||||
|
logger.info("구글 드라이브 업로드 성공 | file_id=%s", file_id)
|
||||||
|
return file_id
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user