Files
o2o-weather/backend/services/external/open_meteo.py
T
skkim 7c12651068 feat: Open-Meteo 구름 20·100km 구 코드 저장, 보조값 수집, 활동 지수 10개에 자외선·햇빛·가시거리 반영
구름
- 노을·일출 점수를 구 중심 20·100km 두 지점으로 계산 (50km 제외), 모델은 JMA·ICON 두 개만 사용
- cloud_hourly를 (구 코드, 방향, 거리, 시각, 모델) 키로 바꾸고 점수에 쓰는 시각만 저장

보조값
- openmeteo_hourly 신규: 자외선·가시거리·돌풍·기압·지표면 온도(끝 시각 값), 일조(3시간 합), 일사(평균·최대)
- worker가 03·09·15·21시 10분에 구 256곳을 요청 11번으로 일괄 수집, 7일 지난 행 정리
- 새 응답에서 값이 비어 오면 이전 값을 유지(COALESCE)

지수
- 새 축 uv·sun·view 추가 (index_definition/index_score 칼럼, 비중 있는 지수에만 상세에 표시)
- 빨래·멍뭉산책·피크닉·등산·러닝·가드닝·별보기·사진산책에 비중 배분, 자전거·캠핑·멍뭉산책에 돌풍·지표면 온도 0점 조건
- 자외선·가시거리 등 순간값은 가장 가까운 3시간 구간, 일조는 덮는 구간을 계산 창에 연결
- 보조값이 새로 오면 지수를 다시 계산하도록 재계산 기준에 fetched_at 추가

테스트 102개 통과 (PGSSLMODE=disable, JWT는 테스트용 환경변수).
2026-10-06 17:21:59 +09:00

114 lines
5.2 KiB
Python

import asyncio
from datetime import datetime, timedelta, timezone
import httpx
from common.enums import CloudModel
URL = "https://api.open-meteo.com/v1/forecast"
MODELS = {"jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
_ATTEMPTS = 3
class OpenMeteoRequestFailed(RuntimeError):
pass
_CHUNK = 24
WEATHER_VARS = (
"uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl",
"sunshine_duration", "shortwave_radiation", "soil_temperature_0cm",
)
SLOT_HOURS = 3
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
"""좌표마다 시간별 층별 구름을 모델 4개로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
params = {
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
"hourly": "cloud_cover_low,cloud_cover_mid,cloud_cover_high",
"models": ",".join(MODELS), "past_days": 1, "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
async def _get_forecast(client: httpx.AsyncClient, params: dict, point_count: int) -> list[dict]:
for attempt in range(_ATTEMPTS):
try:
res = await client.get(URL, params=params)
res.raise_for_status()
data = res.json()
return data if isinstance(data, list) else [data]
except (httpx.HTTPError, ValueError) as e:
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
await asyncio.sleep(1.0 * (attempt + 1))
raise OpenMeteoRequestFailed(f"forecast {point_count} points: {last}")
async def fetch_weather(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 4) -> list[dict]:
"""좌표마다 시간별 자외선·가시거리·돌풍·기압·일조·일사·지면온도 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
params = {
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
"hourly": ",".join(WEATHER_VARS), "wind_speed_unit": "ms", "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
lat, lon = round(point[0], 2), round(point[1], 2)
h = data["hourly"]
rows = []
for i, t in enumerate(h["time"]):
at = datetime.fromisoformat(t).replace(tzinfo=timezone.utc)
for key, model in MODELS.items():
low, mid, high = (h.get(f"cloud_cover_{layer}_{key}", [None] * len(h["time"]))[i] for layer in ("low", "mid", "high"))
if None in (low, mid, high):
continue
rows.append({"lat": lat, "lon": lon, "forecast_at": at, "model": model.value, "cloud_low": low, "cloud_mid": mid, "cloud_high": high})
return rows
def _round(v, digits: int = 0):
return None if v is None else (round(v, digits) if digits else int(round(v)))
def parse_weather(data: dict) -> list[dict]:
"""시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값.
직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀)."""
h = data["hourly"]
times = [datetime.fromisoformat(t).replace(tzinfo=timezone.utc) for t in h["time"]]
index = {t: i for i, t in enumerate(times)}
rows = []
for end, i in index.items():
if end.hour % SLOT_HOURS:
continue
span = [index.get(end - timedelta(hours=k)) for k in range(SLOT_HOURS)]
if None in span:
continue
sun = [h["sunshine_duration"][j] for j in span]
rad = [h["shortwave_radiation"][j] for j in span]
rows.append({
"forecast_at": end,
"uv_index": _round(h["uv_index"][i], 2), "uv_index_clear_sky": _round(h["uv_index_clear_sky"][i], 2),
"visibility_m": _round(h["visibility"][i]), "wind_gust_ms": _round(h["wind_gusts_10m"][i], 1),
"pressure_hpa": _round(h["pressure_msl"][i], 1), "soil_temp_c": _round(h["soil_temperature_0cm"][i], 1),
"sunshine_s": None if None in sun else int(round(sum(sun))),
"shortwave_avg_wm2": None if None in rad else int(round(sum(rad) / len(rad))),
"shortwave_max_wm2": None if None in rad else int(round(max(rad))),
})
return rows