에라모르겠다(‘◇’)?

[Django]시간을 value로 가지고 있는 json 데이터 마지막 시점 이후 데이터 저장하기 본문

Language/Python

[Django]시간을 value로 가지고 있는 json 데이터 마지막 시점 이후 데이터 저장하기

도토리즈 2023. 5. 3. 20:36

업무에 쓸까 하고 짜봤던 코드였는데

전혀 다른 방식으로 진행하게 되어서 블로그에 올려야겠당🤫

 

 

{"timestamp" : "timestamp_value", "value" : "value" } json 모양을 가진 string 형태로 되어있는 데이터를

실행시간.json 파일로 변환하여 저장 후

데이터의 마지막 timestamp 시점을 이용하여 추가되는 timestamp 데이터부터 새로운 .json 파일로 저장하는 코드 

 

[ 해당 데이터는 예시임 ] 

 

- test.txt 파일

- test2.txt 파일

 

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializer import *
from .models import * 
import os
import datetime
import json

@api_view(['post'])
def read_time_value(request) :

    temp_folder = 'C:/Temp_dir/'
    
    # 현재 시간을 기준으로 폴더 경로 생성
    current_date = datetime.date.today().strftime("%Y-%m-%d")
    folder_path = os.path.join(temp_folder, current_date)
    # 폴더가 없는 경우 새로 만들기
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # 새로 저장될 파일 이름 현재 시간으로 생성
    current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    file_name = f"{current_time}.json"
    file_path = os.path.join(folder_path, file_name)
    # 읽은 데이터를 저장할 list 선언
    save_list = []

    # 등록일 내림차순으로 실행일자 = 오늘 날짜인 데이터의 첫번째 값을 status_model 변수의 값으로 지정
    status_model = StatusModel.objects.filter(run_date = current_date).order_by('-reg_dtm').first()

    #status_model이 있는 경우 실행되는 로직
    if status_model :
        get_last_timestamp = status_model.last_timestamp
        print(get_last_timestamp)
        #추가된 timestamp가 있는 경우 txt 파일 읽어오기
        test_file_path = os.getcwd() + '/test_2.txt'
        with open(test_file_path,'r') as f :
            for line in f:
                data = json.loads(line)
                save_list.append(data)

        #새로 추가된 값을 저장할 list 선언
        new_save_list = []
        for i in range(len(save_list)):
            timestamp = save_list[i]['timestamp']
            
            # status_model 에서 가져온 get_last_timestamp의 값보다 새로 읽어온 timestamp 가 더 큰 경우
            # new_save_list 리스트에 저장
            if int(timestamp) > int(get_last_timestamp):
                new_save_list.append(save_list[i])
        print(new_save_list)
        
        if new_save_list  : 
          # 새로 저장할 파일 쓰기
            with open(file_path, "w") as f:
                f.write(json.dumps(new_save_list))

            last_data = new_save_list[-1]
            last_timestamp = last_data['timestamp']
            last_value = last_data['value']

            status = {}
            status['last_timestamp'] = last_timestamp
            status['last_value'] = last_value
            status['last_file_name'] = file_name

            status_ser = StatusSerializer(data=status)
            if status_ser.is_valid() :
                status_ser.save()
            
            return Response(new_save_list)
        
        else : 
            return Response([])        
    #status_model이 없는 경우 실행되는 로직
    else : 
        #txt 파일 읽어오기
        test_file_path = os.getcwd() + '/test.txt'
        with open(test_file_path,'r') as f :
            for line in f:
                data = json.loads(line)
                save_list.append(data)

        last_data = save_list[-1]
        last_timestamp = last_data['timestamp']
        last_value = last_data['value']

        # json 파일 쓰기
        with open(file_path, "w") as f:
            f.write(json.dumps(save_list))

        status = {}
        status['last_timestamp'] = last_timestamp
        status['last_value'] = float(last_value)
        status['last_file_name'] = file_name

        status_ser = StatusSerializer(data=status)

        if status_ser.is_valid() :
             status_ser.save()

    return Response(save_list)

 

-- 초기 select * from python.status 테이블 조회 시 데이터가 없음

-- else 문 실행 후  db 조회 시 첫번째 데이터의 last_timestamp, list_file_name, last_value 저장 

-- 기존 .txt 파일이 Temp_dir/ 실행일 /  실행일_실행시간.json으로 저장됨

 

 

-- db안에 데이터가 있는 경우 if status_model 로직 실행

마찬가지로 db 조회 시 첫번째 데이터의 last_timestamp, list_file_name, last_value 이 저장됨

 

-- 같은 경로에 2번째 .json 파일이 저장됨

 

-- 파일을 확인해보면 test2.txt 파일에는 1682817165000~1682817165012까지의 값이 있지만

test.txt의 last_timestamp인 1682817165004 이후의 값부터 저장됨

 

Comments