./data 폴더를 모니터랑 하고, 새 파일이 생기면 일치하는 파일 형식인지 찾은 후 데이터를 파싱해서 DB에 저장

This commit is contained in:
2025-07-28 16:17:24 +09:00
parent 1e275d2ac7
commit 29319cb12c
4 changed files with 321 additions and 244 deletions

75
lib/file_watch.py Normal file
View File

@ -0,0 +1,75 @@
import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import threading
# pos_update_bill 모듈에서 main 함수를 가져옵니다.
# pos_update_bill.py가 같은 폴더 혹은 PYTHONPATH에 있어야 합니다.
import pos_update_bill
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data'))
# 감시할 파일 확장자 및 패턴 정의 (pos_update_bill.py 내와 일치해야 함)
FILE_EXTENSIONS = ('.xls', '.xlsx')
FILE_PREFIX = "영수증별매출상세현황"
class NewFileHandler(FileSystemEventHandler):
def __init__(self):
super().__init__()
self._lock = threading.Lock()
self._processing_files = set()
def on_created(self, event):
if event.is_directory:
return
filepath = event.src_path
filename = os.path.basename(filepath)
if filename.startswith(FILE_PREFIX) and filename.endswith(FILE_EXTENSIONS):
print(f"[WATCHER] 신규 파일 감지: {filename}")
# 별도의 스레드에서 처리 (감시 중단 방지)
threading.Thread(target=self.process_file, args=(filepath, filename), daemon=True).start()
def process_file(self, filepath, filename):
with self._lock:
if filename in self._processing_files:
print(f"[WATCHER] {filename} 이미 처리 중")
return
self._processing_files.add(filename)
try:
# 파일이 완전히 쓰여질 때까지 대기 (간단히 3초 대기, 필요 시 로직 강화)
time.sleep(3)
print(f"[WATCHER] 파일 처리 시작: {filename}")
# pos_update_bill.main() 내부가 파일 리스트를 탐색해서 처리하므로
# 신규 파일이 존재하는 상태에서 호출하면 정상 동작함.
pos_update_bill.main()
except Exception as e:
print(f"[WATCHER] 파일 처리 중 오류 발생: {filename} / {e}")
else:
try:
os.remove(filepath)
print(f"[WATCHER] 파일 처리 완료 및 삭제: {filename}")
except Exception as e:
print(f"[WATCHER] 파일 삭제 실패: {filename} / {e}")
finally:
with self._lock:
self._processing_files.discard(filename)
def start_watching():
print(f"[WATCHER] {DATA_DIR} 폴더 감시 시작")
event_handler = NewFileHandler()
observer = Observer()
observer.schedule(event_handler, DATA_DIR, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("[WATCHER] 감시 종료 요청 수신, 종료 중...")
observer.stop()
observer.join()
if __name__ == "__main__":
start_watching()