Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fa0695c84 | ||
|
|
5734b57758 | ||
|
|
2fe00c916e | ||
|
|
b889f69135 | ||
|
|
0436971cf1 | ||
|
|
78aad46946 |
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)
|
||||
|
||||
+4
-2
@@ -8,6 +8,8 @@ from services.external.data_go_kr import get_all_items
|
||||
|
||||
REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty"
|
||||
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
||||
# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다.
|
||||
BUDGET_SEC = 45.0
|
||||
|
||||
|
||||
def _int(v) -> Optional[int]:
|
||||
@@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime:
|
||||
|
||||
|
||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"})
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
async def fetch_stations(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"})
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||
|
||||
+5
-4
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict, budget_sec: Optional[float] = None) -> dict:
|
||||
"""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)
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed, budget_sec)
|
||||
|
||||
|
||||
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
|
||||
@@ -44,11 +45,11 @@ async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict)
|
||||
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]:
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000, budget_sec: Optional[float] = None) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page})
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}, budget_sec)
|
||||
raw = body.get("items") or []
|
||||
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
||||
chunk = [chunk] if isinstance(chunk, dict) else chunk
|
||||
|
||||
Vendored
+14
-2
@@ -17,6 +17,15 @@ SOURCE_PREFIX = "popga:"
|
||||
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
|
||||
# 팝가 '축제' 중 연극제·음악제의 공연 한 편. 극장·홀에서 하거나 이름이 공연이면 공연으로 넣는다
|
||||
_SHOW_PLACE = ("극장", "홀", "아트센터", "예술의전당", "씨어터", "시어터", "문화회관", "공연장")
|
||||
_SHOW_NAME = ("연극", "뮤지컬", "오페라", "독주회", "리사이틀", "콘서트")
|
||||
|
||||
|
||||
def is_show(name: str, place: str) -> bool:
|
||||
return any(w in place for w in _SHOW_PLACE) or any(w in name for w in _SHOW_NAME)
|
||||
|
||||
|
||||
_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>")
|
||||
@@ -101,9 +110,12 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
if sido is None:
|
||||
return None
|
||||
geo = loc.get("geo") or {}
|
||||
name, place = html.unescape(ld.get("name") or ""), html.unescape(loc.get("name") or "")
|
||||
if kind is EventKind.FESTIVAL and is_show(name, place):
|
||||
kind = EventKind.CONCERT
|
||||
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_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
|
||||
"place_name": place[: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": kind, "icon": EVENT_ICON[kind],
|
||||
}
|
||||
@@ -43,6 +43,8 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
# 구 코드는 광주·전남을 한 시도(12)로 묶지만, 행사는 TourAPI·문화정보 시도 코드(광주 29 · 전남 46)로 받는다.
|
||||
_EVENT_SIDOS = {"12": ("29", "46")}
|
||||
PLACE_RADIUS_KM = EVENT_RADIUS_KM
|
||||
PLACE_LIMIT = 10
|
||||
# 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다.
|
||||
@@ -129,11 +131,18 @@ def mix_kinds(items: list[EventItem]) -> list[EventItem]:
|
||||
return mixed
|
||||
|
||||
|
||||
def event_sidos(region_code: str) -> tuple[str, ...]:
|
||||
"""구가 속한 시도의 행사 시도 코드들."""
|
||||
sido = region_code[:2]
|
||||
return _EVENT_SIDOS.get(sido, (sido,))
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
"""반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM}
|
||||
return [region.code[:2]] + sorted(near - {region.code[:2]})
|
||||
own = event_sidos(region.code)
|
||||
near = {s for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM for s in event_sidos(r.code)}
|
||||
return list(own) + sorted(near - set(own))
|
||||
|
||||
|
||||
def event_distance(region: Region, e: Event) -> Optional[float]:
|
||||
@@ -148,7 +157,7 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
return distance_km <= EVENT_RADIUS_KM
|
||||
if e.region_code is not None:
|
||||
return e.region_code == region.code
|
||||
return e.sido_code == region.code[:2]
|
||||
return e.sido_code in event_sidos(region.code)
|
||||
|
||||
|
||||
def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]:
|
||||
@@ -193,6 +202,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 +246,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)}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
@@ -158,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]:
|
||||
def key(s: Step) -> float:
|
||||
t = s.time
|
||||
if t[0].isdigit():
|
||||
h = int(t.split("~")[0].split(":")[0])
|
||||
h = int(re.match(r"\d+", t).group())
|
||||
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||
if t.startswith("~"):
|
||||
return 0
|
||||
|
||||
@@ -5,7 +5,8 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external import airkorea, data_go_kr, guard, open_meteo
|
||||
from services.external.airkorea import fetch_realtime
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
@@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch):
|
||||
"""전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다."""
|
||||
monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0)
|
||||
|
||||
async def slow(req: httpx.Request) -> httpx.Response:
|
||||
await asyncio.sleep(0.5)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}})
|
||||
|
||||
async with _client(slow) as client:
|
||||
assert await fetch_realtime(client) == [{"stationName": "x"}]
|
||||
@@ -33,6 +33,11 @@ def test_parse_popup_maps_festival():
|
||||
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
|
||||
|
||||
|
||||
def test_parse_popup_moves_festival_shows_in_theaters_to_concert():
|
||||
page = _page(505, "FESTIVAL", "2026-10-02", "2026-10-11").replace("테스트 빌딩 1F", "대학로예술극장 소극장")
|
||||
assert parse_popup(page, 505, date(2026, 10, 1))["kind"] is EventKind.CONCERT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
|
||||
@@ -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"]
|
||||
@@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch):
|
||||
"""구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다."""
|
||||
today = now_kst().date()
|
||||
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
|
||||
by_sido = {
|
||||
"29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}],
|
||||
"46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}],
|
||||
}
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("29", "46")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json()
|
||||
assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
||||
|
||||
@@ -55,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_morning_rain_then_outdoor_after_it_ends():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps] == ["9~14시", "14시~"]
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
|
||||
@@ -69,7 +69,7 @@ export function Sec({ title, sub, more, className }: SecProps) {
|
||||
|
||||
/** PC(마우스)에서만 보이는 좌우 화살표 */
|
||||
export function Arrows({ api, prev, next, className }: { api: Carousel; prev: boolean; next: boolean; className?: string }) {
|
||||
const btn = 'absolute top-1/2 z-[3] hidden size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)] pointer-fine:grid'
|
||||
const btn = 'absolute top-1/2 z-[3] grid size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)]'
|
||||
return (
|
||||
<>
|
||||
{prev && (
|
||||
|
||||
Reference in new issue
Block a user