본문으로 건너뛰기

[부록] 일별 데이터 업로드 프로그램

활용 사례

mAsh API를 활용해서 데이터를 주기적으로 업로드하는 프로그램을 구현할 수 있습니다.

매일 일정 주기로 매장 방문객 데이터를 조회하여, 다른 데이터베이스로 업로드하는 배치 프로그램을 작성하고자 합니다.

프로그램 작성 가이드

예시에 사용되는 API

  1. 기본 통계 매장 방문 이벤트 데이터 조회
GET /event/place-visit
  • 매장 방문 이벤트 데이터는 일별로 업데이트됩니다. 매장마다 업데이트 시각이 다르며, 현장 이슈 및 메이아이 수집 프로그램의 상황에 따라 업데이트 완료 시각에 차이가 있습니다.
  1. 데이터 업데이트 상태 조회
GET /datasources/apis/update-status/place/last
  • 데이터 업데이트 최종 상태를 조회하여 모든 매장에 업데이트가 완료되었는지 여부에 따라 업로드를 실행하고자 합니다.

코드 예시 (Python)

from datetime import datetime, timedelta
import os
import time


def run_periodically():
"""
일별 배치 프로그램 실행 스크립트
"""
client = MashClient()

# 사용자 인증 및 토큰 획득
client.authenticate(email="user@example.com", password="password123")

# 파일에서 저장된 마지막 실행 날짜 읽기
last_run_date = read_last_run_date()

# 현재 날짜 구하기
today = datetime.now().strftime("%Y-%m-%d")

# 이미 실행한 경우 더 이상 실행하지 않음
if last_run_date == today:
print("이미 실행했습니다.")
return

# 데이터 업데이트 최종 상태 조회 (어제~오늘)
last_update_status = client.get_data(endpoint="/datasources/apis/update-status/place/last")

# 모든 매장의 업데이트가 완료됨 `is_updated: true`
if last_update_status["is_updated"]:
# 업데이트된 방문객 데이터 조회
visit_data_params = {
"start_date": today,
"end_date": today,
}
visit_data = client.get_data(endpoint="/event/place-visit", params=visit_data_params)

# TODO: 이벤트 데이터 업로드 메소드 작성
upload_event_data(visit_data)

# 현재 날짜를 파일에 저장
save_last_run_date(today)
else:
print("데이터 업데이트가 완료되지 않았습니다.")
time.sleep(3600) # 한 시간 뒤 재실행
run_periodically()


def read_last_run_date():
"""
파일에서 저장된 마지막 실행 날짜를 읽어옵니다.
"""
file_path = "last_run_date.txt"

if os.path.exists(file_path):
with open(file_path, "r") as file:
return file.read().strip()
else:
return None

def save_last_run_date(date):
"""
마지막 실행 날짜를 파일에 저장합니다.
"""
file_path = "last_run_date.txt"

with open(file_path, "w") as file:
file.write(date)

# 사용 예시
if __name__ == "__main__":
run_periodically()


주의 사항

주기적으로 반복 실행하는 업로드 프로그램에서 매장 방문 이벤트 데이터가 중복해서 저장되지 않도록 관리 방법을 강구할 필요가 있습니다.

코드 예시에서는 마지막 실행 날짜(last_run_date)를 파일에 저장하고 배치 작업 실행 시각 마다 비교하여, 이미 실행한 경우 더 이상 실행하지 않도록 처리했습니다.