Skip to content

Commit b690862

Browse files
committed
Cicd: Firebase 저장 방식 수정
1 parent 7fe47a0 commit b690862

File tree

2 files changed

+160
-0
lines changed

2 files changed

+160
-0
lines changed

.github/workflows/add_data.yaml

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ jobs:
3333
- name: Add data to Firestore
3434
run: |
3535
python ./rpas/add_data_to_firestore.py
36+
python ./rpas/add_data_to_firestore_v2.py
3637
env:
3738
END_POINT: ${{ secrets.END_POINT }}
3839
SERVICE_KEY: ${{ secrets.SERVICE_KEY }}

rpas/add_data_to_firestore_v2.py

+159
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import sys
2+
import requests
3+
import datetime
4+
import pytz
5+
import os
6+
import time
7+
import json
8+
9+
import firebase_admin
10+
from firebase_admin import credentials
11+
from firebase_admin import firestore
12+
13+
# Firebase FireStore 초기화
14+
cred = credentials.Certificate("serviceAccount.json")
15+
firebase_admin.initialize_app(cred)
16+
db = firestore.client()
17+
18+
19+
# 환경변수 설정
20+
END_POINT = os.environ['END_POINT']
21+
SERVICE_KEY = os.environ['SERVICE_KEY']
22+
23+
# 현재 시간 (End-time)
24+
now = datetime.datetime.now(tz=pytz.timezone('Asia/Seoul'))
25+
26+
# 시작 시간(Start-time, 현재시간 - 15분)
27+
start = now - datetime.timedelta(minutes=15)
28+
29+
# 계측일자 YYYYMMDD (ex: 20240101)
30+
sDate = start.strftime("%Y%m%d")
31+
32+
# 계측시간 HHMM (ex: 0000)
33+
sTime = start.strftime("%H%M")
34+
if start.date() != now.date():
35+
sTime = "0000"
36+
37+
# 계측 종료 일자 HHMM (ex: 1000, max:2400)
38+
eTime = now.strftime("%H%M")
39+
40+
# 염분 수질관측소 코드
41+
wtqltObsrvtCd = {
42+
'하구둑8번교각': "2022B4a",
43+
'하구둑10번교각': "2022B4b",
44+
'갑문상류': "2022B4c",
45+
'을숙도대교P3': "2022B5a",
46+
'을숙도대교P20': "2022B5b",
47+
'낙동강 하구둑': "2022B1a",
48+
'낙동대교': "2022B2a",
49+
'우안배수문': "2022B3a",
50+
'낙동강상류3km': "2022A1a",
51+
'낙동강상류7.5km': "2022A1b",
52+
'낙동강상류9km': "2022A2b",
53+
'낙동강상류10km': "2022A2a"
54+
}
55+
56+
# 한 페이지 결과 수 ()
57+
numOfRows = 100
58+
59+
# 페이지 번호
60+
pageNo = 1
61+
62+
# 데이터 포맷 (json, xml)
63+
_type = "json"
64+
65+
66+
def str_to_float(s: str) -> float:
67+
"""문자열을 실수로 변환하는 함수"""
68+
return float(s.replace(',', ''))
69+
70+
71+
def upload_data_to_firestore(item: dict):
72+
"""데이터를 파이어베이스에 업로드하는 함수"""
73+
74+
# 측정 위치
75+
mesure_location: str = item['obsrvtNm']
76+
mesure_location_code: str = item['wtqltObsrvtCd']
77+
78+
# 측정 시간(계측일자 + 계측시간, KST)
79+
mesure_date: datetime = pytz.timezone(
80+
'Asia/Seoul').localize(datetime.datetime.strptime(str(item['msmtTm']), '%Y%m%d%H%M'))
81+
82+
# 측정 수심)
83+
mesure_depths: float = item['altdDpwt']
84+
if type(mesure_depths) == str:
85+
mesure_depths: float = str_to_float(mesure_depths)
86+
87+
# 측정 염분
88+
mesure_salinity: float = item['saln']
89+
if type(mesure_salinity) == str:
90+
mesure_salinity: float = str_to_float(mesure_salinity)
91+
92+
# 측정 수온
93+
mesure_temperature: float = item['wtep']
94+
if type(mesure_temperature) == str:
95+
mesure_temperature: float = str_to_float(mesure_temperature)
96+
97+
# 파이어베이스 DB 초기화(염분 수질관측소 코드별로)(염분 수질관측소 코드가 없는 경우 생성)
98+
point_collection = db.collection("data").get()
99+
100+
# 파이어베이스 데이터 업로드
101+
point_collection.append({
102+
'mesure_date': mesure_date,
103+
'mesure_location': mesure_location,
104+
'mesure_location_code': mesure_location_code,
105+
'mesure_depths': mesure_depths,
106+
'mesure_salinity': mesure_salinity,
107+
'mesure_temperature': mesure_temperature
108+
})
109+
110+
111+
# 염분 수질관측소 코드별로 반복문 실행
112+
for key in wtqltObsrvtCd:
113+
114+
# 파라미터 설정
115+
print(key, wtqltObsrvtCd[key])
116+
parameters = {
117+
'serviceKey': SERVICE_KEY,
118+
'sDate': sDate,
119+
'sTime': sTime,
120+
'eTime': eTime,
121+
'wtqltObsrvtCd': wtqltObsrvtCd[key],
122+
'numOfRows': numOfRows,
123+
'pageNo': pageNo,
124+
'_type': _type
125+
}
126+
print("parameters: ", parameters)
127+
128+
# API 호출
129+
count = 1
130+
while True:
131+
try:
132+
response = requests.get(url=END_POINT, params=parameters)
133+
print("Response Code: ", response.status_code)
134+
except Exception as e:
135+
print("Error occurred. Retry Count: ", count)
136+
print("Error: ", e)
137+
138+
if response.status_code == 200:
139+
break
140+
141+
time.sleep(1)
142+
143+
# API 응답 데이터 처리
144+
response = json.loads(response.text)
145+
146+
print("Response:", response['response']['header'])
147+
print("data Length: ", response['response']['body']['totalCount'])
148+
149+
if response['response']['body']['totalCount'] == 0:
150+
print("No data")
151+
elif response['response']['body']['totalCount'] == 1:
152+
print("One data")
153+
upload_data_to_firestore(response['response']['body']['items']['item'])
154+
else:
155+
print("Many data")
156+
for data in response['response']['body']['items']['item']:
157+
upload_data_to_firestore(data)
158+
159+
print("Data Upload Success at", wtqltObsrvtCd[key], "\n\n")

0 commit comments

Comments
 (0)