Files
fg-auto/data/weather.py

65 lines
1.9 KiB
Python

# weather.py
import requests
import json
import re
from datetime import datetime
from config import serviceKey, TODAY
def parse_precip(value):
if value == '강수없음':
return 0.0
elif '1mm 미만' in value:
return 0.5
else:
match = re.search(r"[\d.]+", value)
if match:
return float(match.group())
else:
return 0.0
def get_precipitation_summary():
url = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
params = {
'serviceKey': serviceKey,
'numOfRows': '1000',
'pageNo': '1',
'dataType': 'JSON',
'base_date': TODAY,
'base_time': '0800',
'nx': '57',
'ny': '130'
}
response = requests.get(url, params=params)
try:
data = response.json()
total_rainfall = 0.0
lines = [f'<h3 style="font-size:2em; text-align:center;">[시간대별 강수량]</h3>']
lines.append(f'<table style="min-width:400px; border: 1px #333 solid; text-align:center; ">')
lines.append(f'<tr><th>시간</th><th>강수량</th></tr>')
for item in data['response']['body']['items']['item']:
if item['category'] == 'PCP' and item['fcstDate'] == TODAY:
time = item['fcstTime'] # 예: '1100'
if 900 < int(time) < 2300:
mm = parse_precip(item['fcstValue'])
time_str = f"{time[:2]}:{time[2:]}" # '11:00'
lines.append(f"<tr><td>{time_str}</td><td>{mm}mm</td></tr>")
total_rainfall += mm
lines.append("</table>")
lines.append(f"<p>영업시간 중 총 예상 강수량: <strong>{total_rainfall:.1f}mm</strong></p>")
return ''.join(lines)
except json.decoder.JSONDecodeError:
return "⚠️ 응답이 JSON 형식이 아닙니다."
# 테스트용
if __name__ == "__main__":
print(get_precipitation_summary())