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, 문서 파일 이름 정리 등)도 함께 담김.
This commit is contained in:
minaChoi committed 2026-10-07 12:03:48 +09:00
1 parent b61ed92c54
commit 997a366e76
70 files changed
+2083 -649

No files matched your search

+31 -19
View File
@@ -1,22 +1,28 @@
import asyncio
import html
import xml.etree.ElementTree as ET
from datetime import date, datetime, timedelta
from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
from config.settings import settings
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.guard import Unreachable, guarded
# 한국문화정보원 한눈에보는문화정보조회서비스 (분야별 목록). 응답은 XML.
REALM_URL = "https://apis.data.go.kr/B553457/cultureinfo/realm2"
EXHIBITION = "D000"
CONCERT = "B000" # 음악/콘서트
_REALM_KIND = {EXHIBITION: EventKind.EXHIBITION, CONCERT: EventKind.CONCERT}
# event.source_id 접두어. TourAPI contentid(숫자)와 겹치지 않게 한다.
SOURCE_PREFIX = "kcis:"
IMAGE_CREDIT = "ⓒ한국문화정보원"
_PAGE_SIZE = 100
_ATTEMPTS = 3
_BACKOFF_SEC = 1.5
_BACKOFF_SEC = 1.0
_PAGE_GAP_SEC = 1.0 # 쪽을 쉬지 않고 받으면 초당 요청 제한(코드 23)에 걸린다
# 법정동 시도 코드 앞 두 자리 → 문화정보 API 의 sido 값
SIDO_NAME = {
@@ -29,6 +35,10 @@ async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict]
"""한 쪽을 받아 (item 목록, totalCount). 로그·예외에 키를 남기지 않는다."""
if not settings.data_go_kr_service_key:
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
return await guarded("datagokr:realm2", lambda: _try_page(client, params), DataGoKrRequestFailed)
async def _try_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict], int]:
last = ""
for attempt in range(_ATTEMPTS):
try:
@@ -36,28 +46,28 @@ async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict]
root = ET.fromstring(res.content)
except (httpx.HTTPError, ET.ParseError) as e:
last = type(e).__name__
else:
reason = root.findtext(".//returnReasonCode")
if reason:
raise DataGoKrRequestFailed(f"realm2 {reason} {root.findtext('.//errMsg')}")
code = root.findtext(".//resultCode")
if code not in (None, "00", "0000"):
raise DataGoKrRequestFailed(f"realm2 {code} {root.findtext('.//resultMsg')}")
if res.status_code == 200:
items = [{c.tag: (c.text or "").strip() for c in it} for it in root.iter("item")]
return items, int(root.findtext(".//totalCount") or 0)
last = f"HTTP {res.status_code}"
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
continue
reason = root.findtext(".//returnReasonCode")
if reason:
raise DataGoKrRequestFailed(f"realm2 {reason} {root.findtext('.//errMsg')}")
code = root.findtext(".//resultCode")
if code not in (None, "00", "0000"):
raise DataGoKrRequestFailed(f"realm2 {code} {root.findtext('.//resultMsg')}")
if res.status_code == 200:
items = [{c.tag: (c.text or "").strip() for c in it} for it in root.iter("item")]
return items, int(root.findtext(".//totalCount") or 0)
last = f"HTTP {res.status_code}"
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
raise DataGoKrRequestFailed(f"realm2 failed after {_ATTEMPTS} attempts: {last}")
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last}")
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int) -> list[dict]:
"""시도의 전시(미술관·박물관 등) 중 since~since+days 사이에 열리는 것."""
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int, realm: str = EXHIBITION) -> list[dict]:
"""시도의 realm 분야(기본 전시) 중 since~since+days 사이에 열리는 것."""
sido = SIDO_NAME.get(sido_code)
if sido is None:
return []
params = {"realmCode": EXHIBITION, "sido": sido, "from": since.strftime("%Y%m%d"), "to": (since + timedelta(days=days)).strftime("%Y%m%d")}
params = {"realmCode": realm, "sido": sido, "from": since.strftime("%Y%m%d"), "to": (since + timedelta(days=days)).strftime("%Y%m%d")}
items: list[dict] = []
page = 1
while True:
@@ -66,6 +76,7 @@ async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: da
if not chunk or len(items) >= total:
return items
page += 1
await asyncio.sleep(_PAGE_GAP_SEC)
def _date(v: Optional[str]) -> Optional[date]:
@@ -83,7 +94,7 @@ def _coord(v: Optional[str]) -> Optional[float]:
return None
def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[dict]:
def parse_exhibitions(items: list[dict], sido_code: str, since: date, realm: str = EXHIBITION) -> list[dict]:
rows: dict[str, dict] = {}
for it in items:
start, end = _date(it.get("startDate")), _date(it.get("endDate"))
@@ -94,8 +105,9 @@ def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[di
lat, lon = (y, x) if x is None or y is None or x > y else (x, y)
source_id = f"{SOURCE_PREFIX}{it['seq']}"
rows.setdefault(source_id, {
"source_id": source_id, "sido_code": sido_code, "name": it.get("title", "")[:60], "place_name": (it.get("place") or "")[:60],
"source_id": source_id, "sido_code": sido_code, "name": html.unescape(it.get("title", ""))[:60], "place_name": html.unescape(it.get("place") or "")[:60],
"start_date": start, "end_date": end, "is_confirmed": True, "source_url": None,
"image_url": (it.get("thumbnail") or "").replace("http://", "https://", 1) or None, "lat": lat, "lon": lon,
"kind": _REALM_KIND[realm], "icon": EVENT_ICON[_REALM_KIND[realm]],
})
return list(rows.values())
+11 -5
View File
@@ -3,9 +3,10 @@ import asyncio
import httpx
from config.settings import settings
from services.external.guard import Unreachable, guarded
_ATTEMPTS = 3
_BACKOFF_SEC = 1.5
_BACKOFF_SEC = 1.0
class DataGoKrNotConfigured(RuntimeError):
@@ -17,15 +18,20 @@ class DataGoKrRequestFailed(RuntimeError):
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도한다. 로그·예외에 키를 남기지 않는다."""
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
if not settings.data_go_kr_service_key:
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
op = url.rsplit("/", 1)[-1]
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed)
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
last = ""
for attempt in range(_ATTEMPTS):
try:
res = await client.get(url, params={"serviceKey": settings.data_go_kr_service_key, **params})
data = res.json() if res.status_code == 200 else None
last = "" if data else f"HTTP {res.status_code}"
except (httpx.HTTPError, ValueError) as e:
data, last = None, type(e).__name__
if data and "response" in data:
@@ -33,9 +39,9 @@ async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
if header.get("resultCode", "00") not in ("00", "0000"):
raise DataGoKrRequestFailed(f"{op} {header.get('resultCode')} {header.get('resultMsg')}")
return data["response"]["body"]
last = last or f"HTTP {res.status_code}"
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
raise DataGoKrRequestFailed(f"{op} failed after {_ATTEMPTS} attempts: {last}")
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last or 'unexpected body'}")
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000) -> list[dict]:
+46
View File
@@ -0,0 +1,46 @@
import asyncio
from typing import Awaitable, Callable, Optional, TypeVar
from redis.exceptions import RedisError
from common.cache.redis_client import REDIS
from common.logger import LOG
T = TypeVar("T")
BUDGET_SEC = 8.0 # 재시도까지 합쳐 한 번 호출에 기다리는 최대 시간
DOWN_SEC = 120 # 응답이 없던 API 는 이 시간 동안 부르지 않고 바로 실패로 돌린다
class Unreachable(Exception):
"""재시도해도 응답을 못 받음 (연결 실패·HTTP 오류). API 가 준 오류 코드와 달리 '잠시 쉬기' 대상이다."""
async def _is_down(name: str) -> bool:
try:
return bool(await REDIS.conn.exists(f"apidown:{name}"))
except RedisError as e:
LOG.error(f"[api] {name} down check: {e}")
return False
async def _mark_down(name: str, reason: str) -> None:
LOG.error(f"[api] {name} 응답 없음, {DOWN_SEC}초 동안 부르지 않음: {reason}")
try:
await REDIS.conn.set(f"apidown:{name}", reason[:200], ex=DOWN_SEC)
except RedisError as e:
LOG.error(f"[api] {name} mark down: {e}")
async def guarded(name: str, call: Callable[[], Awaitable[T]], fail: type[Exception], budget_sec: Optional[float] = None) -> T:
"""외부 API 호출을 budget_sec 안에 끝내고, 응답이 없던 API 는 DOWN_SEC 동안 기다리지 않고 바로 fail 을 던진다."""
if await _is_down(name):
raise fail(f"{name} skipped: no answer within the last {DOWN_SEC}s")
budget_sec = budget_sec or BUDGET_SEC
try:
async with asyncio.timeout(budget_sec):
return await call()
except (TimeoutError, Unreachable) as e:
reason = str(e) or f"no answer within {budget_sec:.0f}s"
await _mark_down(name, reason)
raise fail(f"{name} {reason}") from None
+11 -4
View File
@@ -4,10 +4,12 @@ from datetime import datetime, timezone
import httpx
from common.enums import CloudModel
from services.external.guard import Unreachable, guarded
URL = "https://api.open-meteo.com/v1/forecast"
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
_ATTEMPTS = 3
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
class OpenMeteoRequestFailed(RuntimeError):
@@ -20,8 +22,12 @@ _CHUNK = 24
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
"""좌표마다 시간별 층별 구름을 모델 4개로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
async def all_chunks() -> list[dict]:
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
return await guarded("openmeteo", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
@@ -39,8 +45,9 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
return data if isinstance(data, list) else [data]
except (httpx.HTTPError, ValueError) as e:
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
await asyncio.sleep(1.0 * (attempt + 1))
raise OpenMeteoRequestFailed(f"forecast {len(points)} points: {last}")
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(1.0 * (attempt + 1))
raise Unreachable(f"forecast {len(points)} points: {last}")
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
+107
View File
@@ -0,0 +1,107 @@
import asyncio
import html
import json
import re
from datetime import date
from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
# 팝가(popga.co.kr) 팝업스토어. 공개 API 가 없어 robots.txt 가 허용하는 사이트맵·상세 페이지를 읽는다.
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
POPUP_URL = "https://popga.co.kr/popup/{id}"
SOURCE_PREFIX = "popga:"
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
REQUEST_GAP_SEC = 0.3
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
_URL = re.compile(r"<url>(.*?)</url>", re.S)
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
_POPUP_PATH = re.compile(r"^https://popga\.co\.kr/popup/(\d+)$")
_LD_JSON = re.compile(r'<script[^>]*application/ld\+json[^>]*>(.*?)</script>', re.S)
_SIDO = {
"서울": "11", "부산": "26", "대구": "27", "인천": "28", "광주": "29", "대전": "30", "울산": "31", "세종": "36", "경기": "41",
"충북": "43", "충남": "44", "전남": "46", "경북": "47", "경남": "48", "제주": "50", "강원": "51", "전북": "52",
"충청북도": "43", "충청남도": "44", "전라남도": "46", "경상북도": "47", "경상남도": "48", "전라북도": "52",
}
async def fetch_popup_index(client: httpx.AsyncClient) -> dict[int, str]:
"""사이트맵 전체에서 팝업 상세 페이지 {id: lastmod}."""
res = await client.get(SITEMAP_URL)
res.raise_for_status()
found: dict[int, str] = {}
for sitemap in _LOC.findall(res.text):
await asyncio.sleep(REQUEST_GAP_SEC)
part = await client.get(sitemap)
part.raise_for_status()
for block in _URL.findall(part.text):
loc, mod = _LOC.search(block), _LASTMOD.search(block)
m = _POPUP_PATH.match(loc.group(1)) if loc else None
if m:
found[int(m.group(1))] = mod.group(1) if mod else ""
return found
async def fetch_popup_page(client: httpx.AsyncClient, popup_id: int) -> str:
res = await client.get(POPUP_URL.format(id=popup_id))
res.raise_for_status()
return res.text
def sido_of(address: str) -> Optional[str]:
"""주소 첫 낱말("서울", "서울특별시", "경상남도")로 시도 코드."""
first = (address or "").split(" ", 1)[0]
if first in _SIDO:
return _SIDO[first]
return next((code for name, code in _SIDO.items() if len(name) == 2 and first.startswith(name)), None)
def _event_ld(page: str) -> Optional[dict]:
for block in _LD_JSON.findall(page):
try:
data = json.loads(block)
except json.JSONDecodeError:
continue
if isinstance(data, dict) and data.get("@type") == "Event":
return data
return None
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_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
ld = _event_ld(page)
if kind is None or kind.group(1) != STORE 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:
return None
loc = ld.get("location") or {}
sido = sido_of((loc.get("address") or {}).get("streetAddress", ""))
if sido is None:
return None
geo = loc.get("geo") or {}
return {
"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],
}
+44
View File
@@ -0,0 +1,44 @@
import httpx
from common.logger import LOG
from config.settings import settings
TIMEOUT_SEC = 10.0
def _card(title: str, detail: str) -> dict:
"""Adaptive Card 1.2 — Teams Workflows 수신 webhook 이 받는 최소 모양."""
return {
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": None,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": True},
{"type": "TextBlock", "text": detail, "wrap": True},
],
},
}],
}
async def send(title: str, detail: str) -> bool:
"""TEAMS_WEBHOOK_URL 이 있을 때만 보낸다. 로그에 주소를 남기지 않는다."""
url = settings.teams_webhook_url.strip()
if not url:
return False
if not url.startswith("https://"):
LOG.error("[teams] TEAMS_WEBHOOK_URL 이 https 가 아니다")
return False
try:
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, follow_redirects=False) as client:
res = await client.post(url, json=_card(title, detail))
res.raise_for_status()
return True
except httpx.HTTPError as e:
LOG.error(f"[teams] send failed: {type(e).__name__}")
return False
+2 -1
View File
@@ -3,6 +3,7 @@ from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
from services.external.data_go_kr import get_all_items
FESTIVAL_URL = "https://apis.data.go.kr/B551011/KorService2/searchFestival2"
@@ -36,6 +37,6 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
"source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60],
"place_name": (it.get("addr1") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None,
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")),
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
})
return rows