시간대별 강수량 정보를 html형식으로 출력하도록 변경

This commit is contained in:
2025-06-27 13:32:19 +09:00
parent 2383f6ebb6
commit cb1a98d940

View File

@ -1,25 +1,10 @@
# weather.py
import requests
import json
import re
from datetime import datetime
base_date = datetime.now().strftime('%Y%m%d') # 오늘 날짜
serviceKey = 'mHrZoSnzVc+2S4dpCe3A1CgI9cAu1BRttqRdoEy9RGbnKAKyQT4sqcESDqqY3grgBGQMuLeEgWIS3Qxi8rcDVA=='
url = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
params = {
'serviceKey': serviceKey,
'numOfRows': '1000',
'pageNo': '1',
'dataType': 'JSON',
'base_date': base_date,
'base_time': '0800', # 02:00 부터 3시간 단위 발표
'nx': '57',
'ny': '130'
}
response = requests.get(url, params=params)
from config import serviceKey, TODAY
def parse_precip(value):
if value == '강수없음':
@ -27,30 +12,49 @@ def parse_precip(value):
elif '1mm 미만' in value:
return 0.5
else:
# 숫자만 추출 (예: '1.0mm' → 1.0)
match = re.search(r"[\d.]+", value)
if match:
return float(match.group())
else:
return 0.0
try:
data = response.json()
total_rainfall = 0.0
def get_precipitation_summary():
url = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
print("📅 시간대별 강수량 (단기예보 기준):")
params = {
'serviceKey': serviceKey,
'numOfRows': '1000',
'pageNo': '1',
'dataType': 'JSON',
'base_date': TODAY,
'base_time': '0800',
'nx': '57',
'ny': '130'
}
for item in data['response']['body']['items']['item']:
if item['category'] == 'PCP' and item['fcstDate'] == base_date:
time = item['fcstTime']
if 900 < int(time) < 2300:
value = item['fcstValue']
mm = parse_precip(value)
print(f" {time}시 → {mm}mm")
total_rainfall += mm
response = requests.get(url, params=params)
print(f"\n🌧️ 총 예상 강수량: {total_rainfall:.1f}mm")
try:
data = response.json()
total_rainfall = 0.0
lines = [f"<p>📅 시간대별 강수량 :</p><ul>"]
except json.decoder.JSONDecodeError:
print("⚠️ 응답이 JSON 형식이 아닙니다.")
print(response.text)
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'])
lines.append(f"<li>{time}시 → {mm}mm</li>")
total_rainfall += mm
lines.append("</ul>")
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())