Files
fg-auto/data/weather.py
2025-06-27 15:25:46 +09:00

78 lines
2.8 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(retry=True):
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 = [
'<div class="weatherinfo" style="max-width: 100%; overflow-x: auto; padding: 10px; box-sizing: border-box;">',
'<h3 style="font-size: 1.8em; text-align: center; margin: 20px 0;">[시간대별 예상 강수량]</h3>',
'<table style="border-collapse: collapse; width: 100%; max-width: 400px; margin: 0 auto; font-size: 1em;">',
'<thead>',
'<tr>',
'<th style="border: 1px solid #333; padding: 2px;background-color: #f0f0f0;">시간</th>',
'<th style="border: 1px solid #333; padding: 2px;background-color: #f0f0f0;">강수량</th>',
'</tr>',
'</thead>',
'<tbody>'
]
for item in data['response']['body']['items']['item']:
if item['category'] == 'PCP' and item['fcstDate'] == TODAY:
time = item['fcstTime']
if 900 < int(time) < 2300:
mm = parse_precip(item['fcstValue'])
time_str = f"{time[:2]}:{time[2:]}"
lines.append(f'<tr><td style="border: 1px solid #333; padding: 2px;text-align: center;">{time_str}</td><td style="border: 1px solid #333; padding: 2px;text-align: center;">{mm}mm</td></tr>')
total_rainfall += mm
lines.append(f'<tr><td colspan="2" style="border: 1px solid #333; padding: 2px;text-align: center; font-weight: bold;">영업시간 중 총 예상 강수량: {total_rainfall:.1f}mm</td></tr>')
lines.append('</tbody></table><p style="text-align:right; font-size: 0.8em;">08:00 파주 조리읍 기상청 단기예보 기준</div>')
return ''.join(lines)
except json.decoder.JSONDecodeError:
if retry:
print("⚠️ JSON 디코드 오류 발생, 재시도 중...")
return get_precipitation_summary(retry=False)
else:
return "⚠️ 응답이 JSON 형식이 아닙니다."
# 테스트용
if __name__ == "__main__":
print(get_precipitation_summary())