Files
o2o-weather/backend/router/v1/index/index.py
T
minaChoi 997a366e76 feat: 축제·전시·콘서트·팝업 7일마다 수집, 피드 행사 종류 섞기
- 행사 수집을 화면 요청에서 빼고 worker 가 월 04:00(켤 때 7일 기록 없으면 한 번) 전국 17개 시도를 받는다
- 문화정보원 음악/콘서트(B000) 추가, 쪽·시도 사이 1초 간격으로 초당 요청 제한 회피
- 팝가(popga.co.kr) 팝업스토어 수집: 사이트맵 + 상세 JSON-LD, 바뀐 페이지만 다시 읽음
- 수집이 끝나면 Teams Workflows webhook 으로 종류별 건수 알림 (TEAMS_WEBHOOK_URL)
- event.kind(1=축제 2=전시 3=콘서트 4=팝업) 칸과 종류별 아이콘 추가
- 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 섞음
- 포스트 종류별 내용·피드 기획 문서 갱신

같은 작업 폴더의 다른 작업(외부 API 가드, 노을·달 계산, 각 API, 문서 파일 이름 정리 등)도 함께 담김.
2026-10-07 12:03:48 +09:00

65 lines
3.3 KiB
Python

from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, Path, Query
from common.enums import ErrorType, IndexCategory
from common.models.errors import error_info
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, TrendPoint
from services.calc.index_calc import AXES, axis_label, zero_rules_text
from services.index_service import IndexItem, IndexService, slot_label
router = APIRouter(prefix="/v1/index", tags=["index"])
def _summary(i: IndexItem, today: date) -> IndexSummary:
d = i.definition
return IndexSummary(
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
)
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)")
async def list_indices(
region: str = Query(..., description="구 행정코드"),
category: Optional[IndexCategory] = Query(None),
core: bool = Query(False, description="이번 계절 핵심 지수만"),
service: IndexService = Depends(),
) -> Res_IndexList:
err, board = await service.board(region)
if err is not ErrorType.SUCCESS:
return Res_IndexList(result=error_info(err))
items = [_summary(i, board.day) for i in board.items]
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
@router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거")
async def get_index(index_id: int = Path(...), region: str = Query(..., description="구 행정코드"), service: IndexService = Depends()) -> Res_IndexDetail:
err, board = await service.board(region)
if err is not ErrorType.SUCCESS:
return Res_IndexDetail(result=error_info(err))
item = next((i for i in board.items if i.definition.index_id == index_id), None)
if item is None:
return Res_IndexDetail(result=error_info(ErrorType.NOT_FOUND))
d, s = item.definition, item.score
return Res_IndexDetail(
index=_summary(item, board.day), description=d.description,
factors=[
Factor(axis=a, label=axis_label(a, d.factor_rules), value=getattr(s, f"{a}_score"), weight=getattr(d, f"weight_{a}"), note=s.notes.get(a, ""))
for a in AXES
if getattr(d, f"weight_{a}")
],
zero_rules=zero_rules_text(d.zero_rules), zero_reason=s.zero_reason, limit=d.limit_description,
bands=_bands(d.sentences or {}, s.score),
)
def _bands(sentences: dict, score: int) -> list[ScoreBand]:
"""seed 의 sentences {"0": ..., "30": ..., "60": ..., "80": ...} 를 구간으로. 키는 구간 시작 점수."""
lows = sorted(int(k) for k in sentences)
highs = [lo - 1 for lo in lows[1:]] + [100]
return [ScoreBand(low=lo, high=hi, text=sentences[str(lo)], current=lo <= score <= hi) for lo, hi in zip(lows, highs)]