69 lines
2.8 KiB
Python
69 lines
2.8 KiB
Python
import asyncio
|
|
import html
|
|
import re
|
|
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
|
|
# 이름 앞 주최 기관 "[서울시청] ", "[마포문화재단] " 은 카드 제목에서 뗀다
|
|
_HOST_PREFIX = re.compile(r"^(\s*\[[^\]]*\]\s*)+")
|
|
|
|
|
|
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 = _HOST_PREFIX.sub("", 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
|