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>
This commit is contained in:
1 parent
9cdc0d8fea
commit
e134295ce5
135 files changed
+9123
No files matched your search
+57
@@ -0,0 +1,57 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import CloudModel
|
||||
|
||||
URL = "https://api.open-meteo.com/v1/forecast"
|
||||
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
|
||||
_ATTEMPTS = 3
|
||||
|
||||
|
||||
class OpenMeteoRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
_CHUNK = 24
|
||||
|
||||
|
||||
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",
|
||||
}
|
||||
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 {len(points)} points: {last}")
|
||||
|
||||
|
||||
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
|
||||
Reference in new issue
Block a user