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
@@ -0,0 +1,73 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import AirQuality, Region
|
||||
from common.enums import AirGrade, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import haversine_km
|
||||
from crud.air_crud import AirCRUD
|
||||
from services.external.airkorea import fetch_realtime, fetch_stations, parse_realtime, parse_stations
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
|
||||
_AIR_DELAY = timedelta(minutes=20)
|
||||
_RETRY_SEC = 600
|
||||
_NEAREST = 5
|
||||
GRADE_LABEL = {AirGrade.GOOD: "좋음", AirGrade.NORMAL: "보통", AirGrade.BAD: "나쁨", AirGrade.VERY_BAD: "매우나쁨"}
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
class AirService:
|
||||
def __init__(self, crud: AirCRUD = Depends(AirCRUD)) -> None:
|
||||
self.crud = crud
|
||||
|
||||
async def ensure(self, now: datetime) -> None:
|
||||
"""이번 시각(매시 20분 이후) 측정값이 없으면 전국을 다시 받는다. 갱신이 늦으면 10분 동안은 다시 부르지 않는다."""
|
||||
expected = (now - _AIR_DELAY).replace(minute=0, second=0, microsecond=0)
|
||||
err, latest = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_measured(s))
|
||||
if err is not ErrorType.SUCCESS or (latest is not None and latest >= expected):
|
||||
return
|
||||
try:
|
||||
if not await REDIS.conn.set("air:tried", "1", nx=True, ex=_RETRY_SEC):
|
||||
return
|
||||
except RedisError as e:
|
||||
LOG.error(f"[air] marker: {e}")
|
||||
if latest is None:
|
||||
await self.refresh(with_stations=True)
|
||||
return
|
||||
task = asyncio.create_task(self.refresh(with_stations=False))
|
||||
_background.add(task)
|
||||
task.add_done_callback(_background.discard)
|
||||
|
||||
async def refresh(self, with_stations: bool) -> None:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
stations = parse_stations(await fetch_stations(client)) if with_stations else []
|
||||
quality = parse_realtime(await fetch_realtime(client))
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[air] refresh: {e}")
|
||||
return
|
||||
fns = [lambda s: self.crud.upsert_quality(s, quality)]
|
||||
if stations:
|
||||
fns.insert(0, lambda s: self.crud.replace_stations(s, stations))
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(fns)
|
||||
LOG.info(f"[air] stations {len(stations)} quality {len(quality)}: {err.name}")
|
||||
|
||||
async def nearest(self, region: Region) -> Optional[AirQuality]:
|
||||
"""구 중심에서 가까운 측정소 5곳 중 초미세먼지 값이 있는 가장 가까운 곳."""
|
||||
err, stations = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.stations(s))
|
||||
if err is not ErrorType.SUCCESS or not stations:
|
||||
return None
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = sorted(stations, key=lambda st: haversine_km(lat, lon, float(st.lat), float(st.lon)))[:_NEAREST]
|
||||
err, qualities = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.qualities(s, [st.station_name for st in near]))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return None
|
||||
by_name = {q.station_name: q for q in qualities}
|
||||
return next((by_name[st.station_name] for st in near if st.station_name in by_name and by_name[st.station_name].pm25 is not None), None)
|
||||
Reference in new issue
Block a user