fix: 같은 축제가 다른 출처로 이미 있으면 넣지 않기 (이름 같고 기간 겹침)
This commit is contained in:
1 parent
0436971cf1
commit
b889f69135
3 files changed
+45
-2
No files matched your search
@@ -21,7 +21,7 @@ from services.external.culture_api import SIDO_NAME
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.week_service import collect_events
|
||||
from services.week_service import collect_events, drop_known
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
|
||||
@@ -105,6 +105,7 @@ async def build_today_feed() -> ErrorType:
|
||||
|
||||
|
||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
||||
rows = await drop_known(rows)
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
if err is ErrorType.SUCCESS and seen:
|
||||
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
||||
|
||||
@@ -193,6 +193,26 @@ def _name_key(name: str) -> str:
|
||||
return _NAME_NOISE.sub("", name).lower()
|
||||
|
||||
|
||||
async def drop_known(rows: list[dict]) -> list[dict]:
|
||||
"""다른 출처로 이미 들어 있는 행사(같은 시도, 이름이 같고 기간이 겹침)는 뺀다. 먼저 넣은 출처를 남긴다."""
|
||||
if not rows:
|
||||
return rows
|
||||
since, until = min(r["start_date"] for r in rows), max(r["end_date"] for r in rows)
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(lambda s: WeekCRUD().events(s, sorted({r["sido_code"] for r in rows}), since, until))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return rows
|
||||
known: dict[tuple[str, str], list[Event]] = {}
|
||||
for e in existing or []:
|
||||
known.setdefault((e.sido_code, _name_key(e.name)), []).append(e)
|
||||
|
||||
def dup(r: dict) -> bool:
|
||||
key = _name_key(r["name"])
|
||||
return bool(key) and any(e.source_id != r["source_id"] and e.start_date <= r["end_date"] and r["start_date"] <= e.end_date
|
||||
for e in known.get((r["sido_code"], key), []))
|
||||
|
||||
return [r for r in rows if not dup(r)]
|
||||
|
||||
|
||||
async def _seoul(client: httpx.AsyncClient, sido: str, today: date, known: list[dict]) -> list[dict]:
|
||||
"""서울문화포털 축제(동네·구청·공원 행사). TourAPI 에 이미 있는 축제는 뺀다. 실패해도 다른 출처는 그대로 넣는다."""
|
||||
if sido != SEOUL:
|
||||
@@ -217,7 +237,7 @@ async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, i
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[week] events {sido}: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, {}
|
||||
rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values())
|
||||
rows = await drop_known(list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values()))
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
|
||||
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
|
||||
|
||||
@@ -59,3 +59,25 @@ async def test_seoul_failure_keeps_other_sources(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
|
||||
assert await _seoul(None, "11", date(2026, 10, 8), []) == []
|
||||
|
||||
|
||||
def _row(source_id, name, start, end, sido="11"):
|
||||
return {"source_id": source_id, "sido_code": sido, "name": name, "place_name": "", "start_date": start, "end_date": end,
|
||||
"is_confirmed": True, "source_url": None, "image_url": None, "lat": None, "lon": None, "kind": 1, "icon": "fireworks"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_drop_known_skips_same_festival_from_another_source():
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.week_service import drop_known
|
||||
|
||||
tour = _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 24))
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [tour])])
|
||||
rows = [
|
||||
_row("popga:1", "2026 경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10)),
|
||||
_row("popga:2", "경복궁 별빛야행", date(2026, 11, 1), date(2026, 11, 2)),
|
||||
_row("popga:3", "경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10), sido="41"),
|
||||
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
|
||||
]
|
||||
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
|
||||
Reference in new issue
Block a user