- 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>
90 lines
4.3 KiB
Python
90 lines
4.3 KiB
Python
from dataclasses import dataclass
|
|
from datetime import date, timedelta
|
|
from typing import Optional
|
|
|
|
import httpx
|
|
from fastapi import Depends
|
|
from redis.exceptions import RedisError
|
|
|
|
from common.cache.lock import redis_lock
|
|
from common.cache.redis_client import REDIS
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import Article, SeasonWeek, SolarTerm
|
|
from common.enums import ArticleCategory, ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.kma_time import now_kst
|
|
from crud.season_crud import SeasonCRUD
|
|
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
|
from services.external.kasi import fetch_solar_terms
|
|
|
|
|
|
@dataclass
|
|
class SeasonWeekView:
|
|
year: int
|
|
week: int
|
|
start: date
|
|
end: date
|
|
headline: str
|
|
poem: Optional[SeasonWeek]
|
|
term_now: Optional[SolarTerm]
|
|
term_next: Optional[SolarTerm]
|
|
progress: Optional[float]
|
|
news: list[Article]
|
|
|
|
|
|
class SeasonService:
|
|
def __init__(self, crud: SeasonCRUD = Depends(SeasonCRUD)) -> None:
|
|
self.crud = crud
|
|
|
|
async def this_week(self) -> tuple[ErrorType, Optional[SeasonWeekView]]:
|
|
today = now_kst().date()
|
|
await self._ensure_terms({today.year - 1, today.year, today.year + 1} if today.month in (1, 12) else {today.year})
|
|
year, week, _ = today.isocalendar()
|
|
start = today - timedelta(days=today.weekday())
|
|
err, terms = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.terms(s, today - timedelta(days=40), today + timedelta(days=40)))
|
|
_, poem = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.week(s, year, week))
|
|
_, news = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.articles(s, today, ArticleCategory.SEASON.value))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
past = [t for t in terms if t.term_date <= today]
|
|
future = [t for t in terms if t.term_date > today]
|
|
now_t, next_t = (past[-1] if past else None), (future[0] if future else None)
|
|
progress = None
|
|
if now_t and next_t:
|
|
progress = round((today - now_t.term_date).days / (next_t.term_date - now_t.term_date).days, 2)
|
|
since_term = f"{now_t.name} 지나 {(today - now_t.term_date).days}일째" if now_t else f"{week}번째 주"
|
|
headline = f"{since_term}, {poem.headline}" if poem is not None else since_term
|
|
return ErrorType.SUCCESS, SeasonWeekView(
|
|
year=year, week=week, start=start, end=start + timedelta(days=6), headline=headline, poem=poem,
|
|
term_now=now_t, term_next=next_t, progress=progress, news=news or [],
|
|
)
|
|
|
|
async def articles(self, category: Optional[ArticleCategory]) -> tuple[ErrorType, list[Article]]:
|
|
today = now_kst().date()
|
|
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.articles(s, today, category.value if category else None))
|
|
|
|
async def article(self, article_id: int) -> tuple[ErrorType, Optional[Article]]:
|
|
err, a = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.article(s, article_id))
|
|
return (ErrorType.NOT_FOUND if err is ErrorType.SUCCESS and a is None else err), a
|
|
|
|
async def _ensure_terms(self, years: set[int]) -> None:
|
|
for year in sorted(years):
|
|
key = f"solar:{year}"
|
|
try:
|
|
if await REDIS.conn.exists(key):
|
|
continue
|
|
err, count = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.term_count(s, year))
|
|
if err is ErrorType.SUCCESS and count >= 24:
|
|
await REDIS.conn.set(key, "1", ex=30 * 86400)
|
|
continue
|
|
async with redis_lock(f"lock:{key}", ttl_sec=60) as acquired:
|
|
if not acquired:
|
|
continue
|
|
async with httpx.AsyncClient(timeout=20) as client:
|
|
rows = [r for m in range(1, 13) for r in await fetch_solar_terms(client, year, m)]
|
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_terms(s, rows)])
|
|
if err is ErrorType.SUCCESS and len(rows) >= 24:
|
|
await REDIS.conn.set(key, "1", ex=30 * 86400)
|
|
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
|
LOG.error(f"[season] solar terms {year}: {e}")
|