feat: 서울문화포털 축제(동네·구청·공원)와 팝가 축제도 수집

This commit is contained in:
minaChoi committed 2026-10-08 11:52:14 +09:00
1 parent ce6efe979a
commit c7152563b9
9 files changed
+178 -9

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
DATA_GO_KR_SERVICE_KEY=
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
TEAMS_WEBHOOK_URL=
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost
+1 -1
View File
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
data_go_kr_service_key: str = ""
teams_webhook_url: str = ""
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
jwt_access_secret: str = ""
jwt_refresh_secret: str = ""
+2 -2
View File
@@ -24,7 +24,7 @@ from services.feed_service import build_feed_day, clear_feed_cache
from services.week_service import collect_events
from services.weekend_rank import WeekendRank
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
_POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
_POPGA_BATCH = 100
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
_EVENTS_TTL_SEC = 7 * 86400
@@ -147,7 +147,7 @@ async def refresh_popups() -> ErrorType:
async def _popup_count() -> int:
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND kind = 4 AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(q))
return n if err is ErrorType.SUCCESS and n is not None else 0
+7 -5
View File
@@ -13,7 +13,8 @@ from common.enums import EVENT_ICON, EventKind
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
POPUP_URL = "https://popga.co.kr/popup/{id}"
SOURCE_PREFIX = "popga:"
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
# 팝가 분류(STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제) 중 받는 것. 공연은 문화정보원에서 따로 받는다
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
REQUEST_GAP_SEC = 0.3
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
@@ -86,10 +87,11 @@ def _coord(v) -> Optional[float]:
def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
"""팝업스토어·축제이고 since 이후에 끝나면 event 행, 아니면 None."""
found = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
kind = _KINDS.get(found.group(1)) if found else None
ld = _event_ld(page)
if kind is None or kind.group(1) != STORE or ld is None:
if kind is None or ld is None:
return None
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
if start is None or end is None or end < since:
@@ -103,5 +105,5 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60],
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": EventKind.POPUP, "icon": EVENT_ICON[EventKind.POPUP],
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
}
+65
View File
@@ -0,0 +1,65 @@
import asyncio
import html
from datetime import date, timedelta
from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
# 서울문화포털 문화행사 중 축제. 공개 API 는 키가 따로 있어 robots.txt 가 허용하는 /culture/culture/ 목록을 읽는다.
LIST_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/jsonList.json"
VIEW_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/view.do?cultcode={code}&menuNo=200010"
IMAGE_URL = "https://culture.seoul.go.kr/cmmn/file/getImage.do?atchFileId={id}&thumb=Y"
IMAGE_CREDIT = "ⓒ서울문화포털"
SOURCE_PREFIX = "seoul:"
SEOUL = "11"
REQUEST_GAP_SEC = 0.3
_MAX_PAGES = 30
async def fetch_seoul_festivals(client: httpx.AsyncClient, since: date, days: int) -> list[dict]:
"""since 부터 days 일 안에 열리는 서울 축제. 한 쪽에 10개씩, 빈 쪽이 나올 때까지."""
form = {"menuNo": "200010", "searchCate": "FESTIVAL", "sdate": since.isoformat(), "edate": (since + timedelta(days=days)).isoformat()}
items: list[dict] = []
for page in range(1, _MAX_PAGES + 1):
res = await client.post(LIST_URL, data={**form, "pageIndex": str(page)})
res.raise_for_status()
chunk = res.json().get("resultList") or []
if not chunk:
break
items.extend(chunk)
await asyncio.sleep(REQUEST_GAP_SEC)
return items
def _date(v) -> Optional[date]:
try:
return date.fromisoformat(str(v)[:10])
except ValueError:
return None
def _coord(v) -> Optional[float]:
try:
return round(float(v), 5) if v not in (None, "") else None
except (TypeError, ValueError):
return None
def parse_seoul_festivals(items: list[dict]) -> list[dict]:
rows = []
for it in items:
start, end = _date(it.get("strtdate")), _date(it.get("endDate"))
name = html.unescape(it.get("title") or "").strip()
if start is None or end is None or not name or it.get("cultcode") is None:
continue
rows.append({
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": VIEW_URL.format(code=it["cultcode"]),
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
"lat": _coord(it.get("xCoord")), "lon": _coord(it.get("yCoord")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
})
return rows
+29
View File
@@ -1,4 +1,5 @@
import asyncio
import re
from dataclasses import dataclass
from datetime import date, timedelta
from typing import Optional
@@ -25,6 +26,10 @@ from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.kasi import fetch_holidays
from services.external.seoul_culture import IMAGE_CREDIT as SEOUL_CREDIT
from services.external.seoul_culture import SEOUL
from services.external.seoul_culture import SOURCE_PREFIX as SEOUL_PREFIX
from services.external.seoul_culture import fetch_seoul_festivals, parse_seoul_festivals
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
from services.external.tour_api import fetch_festivals, parse_festivals
from services.index_service import IndexService
@@ -97,6 +102,8 @@ def image_credit(e: Event) -> Optional[str]:
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
if not e.image_url or e.source_id is None:
return None
if e.source_id.startswith(SEOUL_PREFIX):
return SEOUL_CREDIT
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
@@ -155,11 +162,33 @@ async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str
return []
# 같은 축제를 두 출처가 다르게 적는다: "[성동문화재단] 2026 크리에이티브X성수" ↔ "2026 크리에이티브X성수"
_NAME_NOISE = re.compile(r"\[[^\]]*\]|\([^)]*\)|20\d\d|제\s*\d+\s*회|[^\w]")
def _name_key(name: str) -> str:
return _NAME_NOISE.sub("", name).lower()
async def _seoul(client: httpx.AsyncClient, sido: str, today: date, known: list[dict]) -> list[dict]:
"""서울문화포털 축제(동네·구청·공원 행사). TourAPI 에 이미 있는 축제는 뺀다. 실패해도 다른 출처는 그대로 넣는다."""
if sido != SEOUL:
return []
try:
rows = parse_seoul_festivals(await fetch_seoul_festivals(client, today, EVENT_DAYS))
except (httpx.HTTPError, ValueError) as e:
LOG.error(f"[week] seoul festivals: {type(e).__name__} {e}")
return []
names = {_name_key(r["name"]) for r in known}
return [r for r in rows if _name_key(r["name"]) not in names]
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
try:
async with httpx.AsyncClient(timeout=30) as client:
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
festivals += await _seoul(client, sido, today, festivals)
exhibitions = await _culture(client, sido, today, EXHIBITION)
concerts = await _culture(client, sido, today, CONCERT)
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
+8
View File
@@ -65,6 +65,14 @@ async def _async(v):
return v
@pytest.fixture(autouse=True)
def _no_seoul_crawl(monkeypatch):
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
import services.week_service as week_service
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
@pytest.fixture
def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
+5
View File
@@ -28,6 +28,11 @@ def test_parse_popup_maps_store():
}
def test_parse_popup_maps_festival():
row = parse_popup(_page(504, "FESTIVAL", "2026-10-02", "2026-10-11", "경기 수원시 팔달구 테스트로 1"), 504, date(2026, 10, 1))
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
@pytest.mark.parametrize("kind,end,address", [
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
+60
View File
@@ -0,0 +1,60 @@
from datetime import date
import httpx
import pytest
import services.week_service as week_service
from services.external.seoul_culture import LIST_URL, fetch_seoul_festivals, parse_seoul_festivals
from services.week_service import _seoul
ITEM = {
"cultcode": 159216, "title": "[중랑문화재단] 2026 중랑용마폭포축제", "strtdate": "2026-10-10", "endDate": "2026-10-10",
"atchFileId": "abc", "xCoord": "37.5118239", "yCoord": "127.0591590", "facName": "용마폭포공원", "addr": "서울특별시 중랑구",
}
def test_parse_reads_lat_from_x_and_builds_image_and_link():
[row] = parse_seoul_festivals([ITEM, {**ITEM, "cultcode": None}, {**ITEM, "cultcode": 2, "strtdate": ""}])
assert row["source_id"] == "seoul:159216" and row["sido_code"] == "11"
assert (row["lat"], row["lon"]) == (37.51182, 127.05916)
assert row["place_name"] == "용마폭포공원" and row["start_date"] == date(2026, 10, 10)
assert row["image_url"].endswith("atchFileId=abc&thumb=Y") and "cultcode=159216" in row["source_url"]
@pytest.mark.anyio
async def test_fetch_pages_until_empty(monkeypatch):
monkeypatch.setattr("services.external.seoul_culture.REQUEST_GAP_SEC", 0)
pages = []
def handler(req: httpx.Request) -> httpx.Response:
assert str(req.url) == LIST_URL
page = int(dict(x.split("=") for x in req.content.decode().split("&"))["pageIndex"])
pages.append(page)
return httpx.Response(200, json={"resultList": [ITEM] * 10 if page < 3 else []})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
items = await fetch_seoul_festivals(client, date(2026, 10, 8), 30)
assert len(items) == 20 and pages == [1, 2, 3]
@pytest.mark.anyio
async def test_seoul_skips_festivals_tour_api_already_has_and_other_sidos(monkeypatch):
other = {**ITEM, "cultcode": 2, "title": "2026 서울어텀페스타"}
async def fake(client, since, days):
return [ITEM, other]
monkeypatch.setattr(week_service, "fetch_seoul_festivals", fake)
known = [{"name": "제3회 중랑용마폭포축제"}]
rows = await _seoul(None, "11", date(2026, 10, 8), known)
assert [r["name"] for r in rows] == ["2026 서울어텀페스타"]
assert await _seoul(None, "41", date(2026, 10, 8), known) == []
@pytest.mark.anyio
async def test_seoul_failure_keeps_other_sources(monkeypatch):
async def broken(client, since, days):
raise httpx.ConnectError("down")
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
assert await _seoul(None, "11", date(2026, 10, 8), []) == []