Files
o2o-weather/backend/services/weather_service.py
T
minaChoiandClaude Opus 5.5 e134295ce5 feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)
- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가
- 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시)
- 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리
- 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리
- pytest 66개 (테스트 전용 DB·Redis 사용)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:32:22 +09:00

216 lines
9.5 KiB
Python

import asyncio
from collections import Counter
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import Optional
import httpx
from fastapi import Depends
from common.cache.lock import redis_lock
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Region, SunTime, WeatherHourly
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, latest_vilage_base, now_kst
from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD
from crud.weather_crud import WeatherCRUD
from services.calc.sun import sun_times
from services.calc.weather_calc import discomfort_index, feels_like_c
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.kma import day_start_base, fetch_vilage, parse_vilage
SLOT_HOURS = range(0, 24, 3)
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
_MIN_DAY_HOURS = 8
_background: set[asyncio.Task] = set()
@dataclass
class Slot:
at: datetime
row: Optional[WeatherHourly]
icon: str
tone: SlotTone
note: str
@dataclass
class TodayWeather:
region: Region
day: date
issued_at: Optional[datetime]
headline: str
slots: list[Slot]
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
rows = []
for at, v in hourly.items():
rows.append({
"region_code": region_code, "forecast_at": at, "temp_c": v["temp_c"],
"feels_c": feels_like_c(v["temp_c"], v["humidity"], v["wind_ms"], at.month),
"discomfort_index": discomfort_index(v["temp_c"], v["humidity"]),
"sky": v["sky"].value, "rain_type": v["rain_type"].value, "rain_prob": v["rain_prob"],
"rain_mm": v["rain_mm"], "humidity": v["humidity"], "wind_ms": v["wind_ms"], "issued_at": issued,
})
return rows
def _daily_rows(region_code: str, hourly: dict[datetime, dict], daily: dict[date, dict], issued: datetime) -> list[dict]:
by_day: dict[date, list[dict]] = {}
for at, v in hourly.items():
by_day.setdefault(at.date(), []).append(v)
rows = []
for d, vs in by_day.items():
if len(vs) < _MIN_DAY_HOURS and d not in daily:
continue
temps = [v["temp_c"] for v in vs]
rains = [v["rain_type"] for v in vs if v["rain_type"] is not RainType.NONE]
rows.append({
"region_code": region_code, "forecast_date": d,
"temp_min_c": daily.get(d, {}).get("temp_min_c", min(temps)),
"temp_max_c": daily.get(d, {}).get("temp_max_c", max(temps)),
"sky": Counter(v["sky"] for v in vs).most_common(1)[0][0].value,
"rain_type": (rains[0] if rains else RainType.NONE).value,
"rain_prob": max(v["rain_prob"] for v in vs), "issued_at": issued,
})
return rows
def _slot_view(at: datetime, row: Optional[WeatherHourly], sun: SunTime) -> tuple[str, SlotTone, str]:
if row is None:
return "none", SlotTone.DAY, ""
is_sunset = at <= sun.sunset_at < at + timedelta(hours=3)
is_night = not (sun.sunrise_at <= at + timedelta(hours=1, minutes=30) < sun.dusk_end_at)
rain, sky, temp = RainType(row.rain_type), Sky(row.sky), float(row.temp_c)
tone = SlotTone.SUNSET if is_sunset else SlotTone.NIGHT if is_night else SlotTone.DAY
if rain is not RainType.NONE:
icon = "snow" if rain is RainType.SNOW else "rain"
note = {RainType.SNOW: "눈", RainType.SHOWER: "소나기", RainType.SLEET: "비·눈"}.get(rain, f"비 {row.rain_prob}%")
return icon, tone, note
if is_sunset:
return "sunset", tone, "노을"
if sky is Sky.CLOUDY:
return "cloud", tone, "흐림"
if sky is Sky.PARTLY:
return ("cloud" if is_night else "sun_cloud"), tone, "구름 조금"
if temp <= 10:
return ("stars" if is_night else "sun"), tone, "쌀쌀"
if temp >= 28:
return ("stars" if is_night else "sun"), tone, "더워요"
return ("stars", tone, "맑음") if is_night else ("sun", tone, "햇볕")
def _headline(slots: list[Slot]) -> str:
rows = [s for s in slots if s.row is not None]
if not rows:
return ""
rainy = [s for s in rows if s.row.rain_type != RainType.NONE.value]
if rainy:
return f"{rainy[0].at.astimezone(KST).hour}시쯤부터 비, 우산 챙기세요"
hot = max(rows, key=lambda s: s.row.temp_c)
return f"낮 최고 {round(float(hot.row.temp_c))}°, 저녁 {round(float(rows[-1].row.temp_c))}°"
class WeatherService:
def __init__(
self, regions: RegionCRUD = Depends(RegionCRUD), crud: WeatherCRUD = Depends(WeatherCRUD), sky: SkyCRUD = Depends(SkyCRUD)
) -> None:
self.regions = regions
self.crud = crud
self.sky = sky
async def today(self, region_code: str) -> tuple[ErrorType, Optional[TodayWeather]]:
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
await self.ensure_vilage(region, now)
sun = await self._ensure_sun(region, now.date())
start = kst_midnight(now.date())
err, rows = await DB_SESSION_MNG.execute_lambda(
lambda s: self.crud.hourly_between(s, region.code, start, start + timedelta(days=1))
)
if err is not ErrorType.SUCCESS or sun is None:
return ErrorType.DB_ERROR, None
if not rows:
return ErrorType.EXTERNAL_API_ERROR, None
err, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], now.date()))
sunset_score = next(
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == now.date()), None
)
by_at = {r.forecast_at: r for r in rows}
slots = []
for h in SLOT_HOURS:
at = start + timedelta(hours=h)
row = by_at.get(at)
icon, tone, note = _slot_view(at, row, sun)
if note == "노을" and sunset_score is not None:
note = f"노을 {sunset_score}"
slots.append(Slot(at=at, row=row, icon=icon, tone=tone, note=note))
issued = max((r.issued_at for r in rows), default=None)
return ErrorType.SUCCESS, TodayWeather(region=region, day=now.date(), issued_at=issued, headline=_headline(slots), slots=slots)
async def ensure_vilage(self, region: Region, now: datetime) -> None:
latest = latest_vilage_base(now)
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
if err is not ErrorType.SUCCESS or (issued is not None and issued >= latest):
return
if issued is None:
await self._refresh(region, now, latest, wait=True)
return
task = asyncio.create_task(self._refresh(region, now, latest, wait=False))
_background.add(task)
task.add_done_callback(_background.discard)
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool) -> None:
async with redis_lock(f"lock:vilage:{region.code}") as acquired:
if acquired:
bases = [day_start_base(now.date()), latest] if wait else [latest]
await self._fetch_and_store(region, sorted(set(bases)))
return
if wait:
for _ in range(_WAIT_STEPS):
await asyncio.sleep(_WAIT_SEC)
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
if err is ErrorType.SUCCESS and issued is not None:
return
async def _fetch_and_store(self, region: Region, bases: list[datetime]) -> None:
async with httpx.AsyncClient(timeout=10) as client:
for base in bases:
try:
items = await fetch_vilage(client, region.nx, region.ny, base)
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
LOG.error(f"[weather] {region.code} {e}")
continue
hourly, daily = parse_vilage(items)
hourly_rows = _hourly_rows(region.code, hourly, base)
daily_rows = _daily_rows(region.code, hourly, daily, base)
err = await DB_SESSION_MNG.execute_lambda_run([
lambda s: self.crud.upsert_hourly(s, hourly_rows),
lambda s: self.crud.upsert_daily(s, daily_rows),
])
LOG.info(f"[weather] {region.code} base {base:%m-%d %H}시 hourly {len(hourly_rows)} daily {len(daily_rows)}: {err.name}")
async def _ensure_sun(self, region: Region, d: date) -> Optional[SunTime]:
err, sun = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get_sun(s, region.code, d))
if err is not ErrorType.SUCCESS:
return None
if sun is not None:
return sun
t = sun_times(d, float(region.lat), float(region.lon))
row = {
"region_code": region.code, "sun_date": d, "sunrise_at": t.sunrise_at, "sunset_at": t.sunset_at,
"dusk_end_at": t.dusk_end_at, "sunset_azimuth": t.sunset_azimuth,
}
await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)])
return SunTime(**row)