feat: 계절 지도 자리에 첫눈 지도·해돋이 지도 — 단풍 지도가 끝나면 첫눈 지도(~12/20, 지점 42곳 평년 첫눈 날짜 + 앞으로 7일 눈 예보, GET /v1/season/first-snow), 12/21부터 해돋이 지도(~2월, 명소 50곳 해 뜨는 시각, 12월엔 새해 첫날 기준). 오늘 탭 아이콘·피드 맨 앞 카드(foliage_post 좋아요·댓글 자리를 이어받음)·/first-snow·/sunrise 페이지·공유 이미지. 지도 확대·이동은 mapView.ts 로 꺼내 단풍 지도와 같이 씀 (GA first_snow_open·first_snow_spot·sunrise_open·sunrise_spot·sunrise_day)
This commit is contained in:
1 parent
4e69c4ac44
commit
d7dfc1ba82
30 files changed
+1973
-255
No files matched your search
+27
-1
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -87,6 +87,32 @@ async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[flo
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
async def fetch_snow(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 7) -> list[dict]:
|
||||
"""좌표마다 날짜별(한국 날짜) 눈 오는 양 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
|
||||
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
|
||||
|
||||
async def all_chunks() -> list[dict]:
|
||||
results = await asyncio.gather(*[_fetch_snow_chunk(client, c, days) for c in chunks])
|
||||
return [d for r in results for d in r]
|
||||
|
||||
return await guarded("openmeteo:snow", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
|
||||
|
||||
|
||||
async def _fetch_snow_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),
|
||||
"daily": "snowfall_sum", "forecast_days": days, "timezone": "Asia/Seoul",
|
||||
}
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
def parse_snow(data: dict) -> list[tuple[date, float]]:
|
||||
"""날짜별 눈 오는 양(cm). 값이 없는 날은 뺀다."""
|
||||
d = data["daily"]
|
||||
return [(date.fromisoformat(t), float(v)) for t, v in zip(d["time"], d["snowfall_sum"]) if v is not None]
|
||||
|
||||
|
||||
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
lat, lon = round(point[0], 2), round(point[1], 2)
|
||||
h = data["hourly"]
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"source": "기상청 「계절관측지침(2026.4.)」 부록 기후계절 평년값(1991~2020년) 첫눈. 북춘천은 춘천, 북강릉은 강릉으로 적음. 먼 섬(백령도·울릉도·흑산도)과 평년 첫눈이 해를 넘기는 거제(1/14)는 뺌",
|
||||
"basis": "normal 은 평년 첫눈 날짜(월-일). lat·lon 은 그 도시의 대략 위치(지도에 찍고 눈 예보를 받는 자리). top 은 처음 화면에 이름까지 보이는 대표 지점",
|
||||
"spots": [
|
||||
{ "name": "서울", "region": "서울", "lat": 37.57, "lon": 126.97, "normal": "11-20", "top": true },
|
||||
{ "name": "인천", "region": "인천", "lat": 37.48, "lon": 126.62, "normal": "11-23" },
|
||||
{ "name": "수원", "region": "경기", "lat": 37.27, "lon": 126.99, "normal": "11-21" },
|
||||
{ "name": "파주", "region": "경기", "lat": 37.89, "lon": 126.77, "normal": "11-20" },
|
||||
{ "name": "이천", "region": "경기", "lat": 37.26, "lon": 127.48, "normal": "11-20" },
|
||||
{ "name": "철원", "region": "강원", "lat": 38.15, "lon": 127.3, "normal": "11-18" },
|
||||
{ "name": "춘천", "region": "강원", "lat": 37.95, "lon": 127.75, "normal": "11-21", "top": true },
|
||||
{ "name": "원주", "region": "강원", "lat": 37.34, "lon": 127.95, "normal": "11-21" },
|
||||
{ "name": "대관령", "region": "강원", "lat": 37.68, "lon": 128.72, "normal": "11-05", "top": true },
|
||||
{ "name": "속초", "region": "강원", "lat": 38.25, "lon": 128.56, "normal": "12-10" },
|
||||
{ "name": "강릉", "region": "강원", "lat": 37.8, "lon": 128.86, "normal": "12-07", "top": true },
|
||||
{ "name": "동해", "region": "강원", "lat": 37.51, "lon": 129.12, "normal": "12-11" },
|
||||
{ "name": "태백", "region": "강원", "lat": 37.17, "lon": 128.99, "normal": "11-10" },
|
||||
{ "name": "서산", "region": "충남", "lat": 36.78, "lon": 126.49, "normal": "11-20" },
|
||||
{ "name": "천안", "region": "충남", "lat": 36.78, "lon": 127.12, "normal": "11-19" },
|
||||
{ "name": "보령", "region": "충남", "lat": 36.33, "lon": 126.56, "normal": "11-22" },
|
||||
{ "name": "청주", "region": "충북", "lat": 36.64, "lon": 127.44, "normal": "11-23" },
|
||||
{ "name": "충주", "region": "충북", "lat": 36.97, "lon": 127.95, "normal": "11-24" },
|
||||
{ "name": "추풍령", "region": "충북", "lat": 36.22, "lon": 127.99, "normal": "11-17" },
|
||||
{ "name": "대전", "region": "대전", "lat": 36.37, "lon": 127.37, "normal": "11-20", "top": true },
|
||||
{ "name": "전주", "region": "전북", "lat": 35.82, "lon": 127.15, "normal": "11-29", "top": true },
|
||||
{ "name": "군산", "region": "전북", "lat": 36.0, "lon": 126.76, "normal": "11-26" },
|
||||
{ "name": "남원", "region": "전북", "lat": 35.41, "lon": 127.33, "normal": "11-24" },
|
||||
{ "name": "광주", "region": "광주", "lat": 35.17, "lon": 126.89, "normal": "11-29", "top": true },
|
||||
{ "name": "목포", "region": "전남", "lat": 34.82, "lon": 126.38, "normal": "11-29" },
|
||||
{ "name": "순천", "region": "전남", "lat": 35.02, "lon": 127.37, "normal": "11-24" },
|
||||
{ "name": "여수", "region": "전남", "lat": 34.74, "lon": 127.74, "normal": "12-13" },
|
||||
{ "name": "완도", "region": "전남", "lat": 34.4, "lon": 126.7, "normal": "12-08" },
|
||||
{ "name": "안동", "region": "경북", "lat": 36.57, "lon": 128.71, "normal": "11-29" },
|
||||
{ "name": "구미", "region": "경북", "lat": 36.13, "lon": 128.32, "normal": "11-30" },
|
||||
{ "name": "울진", "region": "경북", "lat": 36.99, "lon": 129.41, "normal": "12-09" },
|
||||
{ "name": "포항", "region": "경북", "lat": 36.03, "lon": 129.38, "normal": "12-18" },
|
||||
{ "name": "대구", "region": "대구", "lat": 35.88, "lon": 128.62, "normal": "12-05", "top": true },
|
||||
{ "name": "거창", "region": "경남", "lat": 35.67, "lon": 127.91, "normal": "12-13" },
|
||||
{ "name": "진주", "region": "경남", "lat": 35.16, "lon": 128.04, "normal": "12-18" },
|
||||
{ "name": "창원", "region": "경남", "lat": 35.17, "lon": 128.57, "normal": "12-27" },
|
||||
{ "name": "통영", "region": "경남", "lat": 34.85, "lon": 128.44, "normal": "12-27" },
|
||||
{ "name": "울산", "region": "울산", "lat": 35.56, "lon": 129.32, "normal": "12-24" },
|
||||
{ "name": "부산", "region": "부산", "lat": 35.1, "lon": 129.03, "normal": "12-23", "top": true },
|
||||
{ "name": "제주", "region": "제주", "lat": 33.51, "lon": 126.53, "normal": "12-10", "top": true },
|
||||
{ "name": "서귀포", "region": "제주", "lat": 33.25, "lon": 126.57, "normal": "12-20" },
|
||||
{ "name": "성산", "region": "제주", "lat": 33.39, "lon": 126.88, "normal": "12-13" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_snow, parse_snow
|
||||
|
||||
# 지점별 평년 첫눈 날짜 (기상청 계절관측지침, 1991~2020). 출처·기준은 파일 안에 적혀 있다
|
||||
SPOTS: list[dict] = json.loads((Path(__file__).parent / "first_snow.json").read_text(encoding="utf-8"))["spots"]
|
||||
|
||||
_DAYS = 7
|
||||
# 하루 눈 오는 양이 이만큼(cm)은 돼야 '눈 예보'로 친다 (0 에 가까운 값은 뺀다)
|
||||
_MIN_CM = 0.1
|
||||
# 눈 예보는 3시간에 한 번만 받는다. 첫 사용자가 볼 때 받아 Redis 에 둔다
|
||||
_KEY = "firstsnow:forecast"
|
||||
_TTL_SEC = 3 * 3600
|
||||
|
||||
|
||||
@dataclass
|
||||
class SnowSpot:
|
||||
name: str
|
||||
region: str
|
||||
lat: float
|
||||
lon: float
|
||||
normal: str
|
||||
top: bool
|
||||
snow_date: Optional[date] = None
|
||||
snow_cm: Optional[float] = None
|
||||
|
||||
|
||||
def first_snow_day(days: list[tuple[date, float]], today: date) -> Optional[tuple[date, float]]:
|
||||
"""오늘부터 눈 예보가 있는 첫 날과 그날 양. 없으면 None."""
|
||||
return next(((d, cm) for d, cm in sorted(days) if d >= today and cm >= _MIN_CM), None)
|
||||
|
||||
|
||||
class FirstSnowService:
|
||||
async def spots(self, now: datetime) -> tuple[bool, list[SnowSpot]]:
|
||||
"""(눈 예보를 받았는지, 지점 목록). 예보를 못 받아도 평년 날짜는 돌려준다."""
|
||||
forecast = await self._forecast()
|
||||
today = now.astimezone(KST).date()
|
||||
out = []
|
||||
for s in SPOTS:
|
||||
hit = first_snow_day(forecast[s["name"]], today) if forecast and s["name"] in forecast else None
|
||||
out.append(SnowSpot(
|
||||
name=s["name"], region=s["region"], lat=s["lat"], lon=s["lon"], normal=s["normal"], top=bool(s.get("top")),
|
||||
snow_date=hit[0] if hit else None, snow_cm=round(hit[1], 1) if hit else None,
|
||||
))
|
||||
return forecast is not None, out
|
||||
|
||||
async def _forecast(self) -> Optional[dict[str, list[tuple[date, float]]]]:
|
||||
"""지점 이름 → 날짜별 눈 오는 양. Redis 에 있으면 그것을, 없으면 Open-Meteo 에서 받아 둔다. 못 받으면 None."""
|
||||
try:
|
||||
cached = await REDIS.conn.get(_KEY)
|
||||
if cached:
|
||||
return {name: [(date.fromisoformat(d), cm) for d, cm in days] for name, days in json.loads(cached).items()}
|
||||
except RedisError as e:
|
||||
LOG.error(f"[first_snow] cache read: {e}")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
data = await fetch_snow(client, [(s["lat"], s["lon"]) for s in SPOTS], _DAYS)
|
||||
except OpenMeteoRequestFailed as e:
|
||||
LOG.error(f"[first_snow] {e}")
|
||||
return None
|
||||
forecast = {s["name"]: parse_snow(d) for s, d in zip(SPOTS, data)}
|
||||
try:
|
||||
await REDIS.conn.set(_KEY, json.dumps({name: [[d.isoformat(), cm] for d, cm in days] for name, days in forecast.items()}), ex=_TTL_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[first_snow] cache write: {e}")
|
||||
return forecast
|
||||
Reference in new issue
Block a user