API-Football 데이터 수집 로직 변경

This commit is contained in:
JinwooKim committed 2026-06-16 09:31:29 +09:00
1 parent 8140cd9e02
commit 7625db36a0
3 files changed
+42 -29

No files matched your search

+29 -15
View File
@@ -15,13 +15,12 @@ from __future__ import annotations
import asyncio
import logging
from datetime import timedelta
import httpx
from sqlalchemy import or_, select
from ..config import settings
from ..domain import ensure_aware, now_utc
from ..domain import now_utc
from ..models import FootballCache, Match
log = logging.getLogger("triplepick.football")
@@ -188,33 +187,47 @@ async def _fetch_h2h(db, client, code_a, id_a, code_b, id_b) -> None:
await _upsert(db, f"h2h:{code_a}-{code_b}", {"rows": rows[-5:]})
# 팀 1건 수집 비용(API 호출 수): 스쿼드 1 + 시즌별 경기. H2H 는 1.
_TEAM_CALLS = 1 + len(_SEASONS)
_H2H_CALLS = 1
# ── 수집 잡 (워커 호출) ─────────────────────────────────────────
async def refresh(db, matches: list[Match], limit: int | None = None) -> int:
"""주어진 경기들의 팀/H2H 캐시를 stale 우선으로 갱신. 갱신한 팀 수 반환."""
async def refresh(db, matches: list[Match]) -> int:
"""경기들의 팀/H2H 캐시를 '아직 없는 것만' 한 번씩 수집한다(fetch-once).
과거 시즌 폼·스쿼드·H2H 는 변하지 않고, 2026 진행 결과는 build_data_block 이
우리 DB 에서 라이브로 읽으므로 팀당 1회 수집이면 충분하다. 무료 한도를 넘지
않도록 하루 호출 예산(football_daily_call_budget) 안에서만 받고, 못 받은 팀은
다음 잡이 이어서 누적한다. 전 팀이 캐시되면 이후 호출 0(자동 무동작).
이번 잡에서 새로 수집한 팀 수 반환."""
if not enabled():
return 0
limit = limit if limit is not None else settings.football_refresh_batch
cutoff = now_utc() - timedelta(hours=settings.football_cache_ttl_hours)
budget = settings.football_daily_call_budget
refreshed = 0
calls = 0
async with httpx.AsyncClient() as client:
seen: set[str] = set()
for m in matches:
for code, name in ((m.team_a_code, m.team_a_name), (m.team_b_code, m.team_b_name)):
if code in seen or refreshed >= limit:
if code in seen:
continue
seen.add(code)
row = await db.get(FootballCache, f"team:{code}")
if row and ensure_aware(row.fetched_at) > cutoff:
continue # 신선 — skip
if await db.get(FootballCache, f"team:{code}"):
continue # 이미 수집됨 — 다시 받지 않음(fetch-once)
if calls + _TEAM_CALLS > budget:
continue # 오늘 호출 예산 소진 — 남은 팀은 다음 잡에서
try:
if await _fetch_team(db, client, code, name):
refreshed += 1
except Exception as e: # noqa: BLE001
log.warning("football: 팀 %s 수집 실패 %s", code, e)
# H2H (양 팀 캐시가 있을 때만)
calls += _TEAM_CALLS # 성공/실패 무관 호출은 소비됨(한도 보호)
# H2H — 양 팀이 캐시됐고 아직 안 받은 쌍만
for m in matches:
h = await db.get(FootballCache, f"h2h:{m.team_a_code}-{m.team_b_code}")
if h and ensure_aware(h.fetched_at) > cutoff:
if calls + _H2H_CALLS > budget:
break
if await db.get(FootballCache, f"h2h:{m.team_a_code}-{m.team_b_code}"):
continue
ta = await db.get(FootballCache, f"team:{m.team_a_code}")
tb = await db.get(FootballCache, f"team:{m.team_b_code}")
@@ -225,9 +238,10 @@ async def refresh(db, matches: list[Match], limit: int | None = None) -> int:
m.team_b_code, tb.payload["team_id"])
except Exception as e: # noqa: BLE001
log.warning("football: H2H %s 수집 실패 %s", m.match_id, e)
calls += _H2H_CALLS
await db.commit()
if refreshed:
log.info("football: 팀 %d개 캐시 갱신", refreshed)
if refreshed or calls:
log.info("football: 신규 팀 %d개 수집 (호출 ~%d/%d)", refreshed, calls, budget)
return refreshed