- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?' - 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준 - 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수 - 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리 - 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정 - 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성 - 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시 - 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집 - 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
96 lines
4.4 KiB
Python
96 lines
4.4 KiB
Python
import asyncio
|
|
import csv
|
|
import json
|
|
import os
|
|
import sys
|
|
from datetime import date
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
from sqlalchemy import update # noqa: E402
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
|
from common.database.model.models import Region # noqa: E402
|
|
from common.enums import ErrorType # noqa: E402
|
|
from crud.index_crud import IndexCRUD # noqa: E402
|
|
from crud.region_crud import RegionCRUD # noqa: E402
|
|
from crud.season_crud import SeasonCRUD # noqa: E402
|
|
from crud.sky_crud import SkyCRUD # noqa: E402
|
|
from crud.week_crud import WeekCRUD # noqa: E402
|
|
|
|
# 출처: 기상청 단기예보 활용가이드 격자·위경도 표(시군구 줄) + 특보구역·중기예보구역 코드표.
|
|
SEED_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed")
|
|
_INT = {"nx", "ny"}
|
|
_FLOAT = {"lat", "lon"}
|
|
|
|
|
|
def read_regions() -> list[dict]:
|
|
with open(os.path.join(SEED_DIR, "region.csv"), encoding="utf-8") as f:
|
|
return [{k: int(v) if k in _INT else float(v) if k in _FLOAT else v for k, v in row.items()} for row in csv.DictReader(f)]
|
|
|
|
|
|
def _read(name: str) -> list[dict]:
|
|
with open(os.path.join(SEED_DIR, name), encoding="utf-8") as f:
|
|
return list(csv.DictReader(f))
|
|
|
|
|
|
def _json(name: str) -> list[dict]:
|
|
with open(os.path.join(SEED_DIR, name), encoding="utf-8") as f:
|
|
return json.load(f)
|
|
|
|
|
|
async def _set_ranking_spots(s, spots: list[dict]) -> None:
|
|
await s.execute(update(Region).values(is_ranking_spot=False, ranking_note=None))
|
|
for row in spots:
|
|
res = await s.execute(update(Region).where(Region.name == row["name"]).values(is_ranking_spot=True, ranking_note=row["note"]))
|
|
if res.rowcount != 1:
|
|
raise ValueError(f"ranking_spot.csv: region not found {row['name']}")
|
|
|
|
|
|
async def main() -> int:
|
|
rows = read_regions()
|
|
code_by_name = {r["name"]: r["code"] for r in rows}
|
|
# source(tourapi contentid·manual)는 출처 기록용이라 DB엔 넣지 않는다. 서쪽이 트인 곳을 sort_order 0 으로 앞세운다.
|
|
spots = [
|
|
{"region_code": code_by_name[r["region_name"]], "name": r["name"], "description": r["description"],
|
|
"lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": 0 if r["west_open"] == "1" else 1}
|
|
for r in _read("sunset_spot.csv")
|
|
]
|
|
places = [
|
|
{"region_code": code_by_name[r["region_name"]], "area": r["area"], "name": r["name"], "is_outdoor": r["is_outdoor"] == "1",
|
|
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r["sort_order"])}
|
|
for r in _read("place.csv")
|
|
]
|
|
# 직접 넣는 행사 (TourAPI 에 없는 것). source_id 가 없는 줄만 이 파일로 바꿔 넣는다.
|
|
events = [
|
|
{"region_code": code_by_name[r["region_name"]], "sido_code": code_by_name[r["region_name"]][:2], "area": r["area"] or None,
|
|
"name": r["name"], "place_name": r["place_name"], "icon": r["icon"], "start_date": date.fromisoformat(r["start_date"]),
|
|
"end_date": date.fromisoformat(r["end_date"]), "is_confirmed": False, "source_url": r["source_url"] or None}
|
|
for r in _read("event.csv")
|
|
]
|
|
articles = [
|
|
{**a, "show_from": date.fromisoformat(a["show_from"]) if a["show_from"] else None,
|
|
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None}
|
|
for a in _json("article.json")
|
|
]
|
|
weeks = _json("season_week.json")
|
|
ranking = _read("ranking_spot.csv")
|
|
indices = _json("index_definition.json")
|
|
err = await DB_SESSION_MNG.execute_lambda_run([
|
|
lambda s: RegionCRUD().upsert_many(s, rows),
|
|
lambda s: _set_ranking_spots(s, ranking),
|
|
lambda s: SkyCRUD().replace_spots(s, spots),
|
|
lambda s: IndexCRUD().upsert_definitions(s, indices),
|
|
lambda s: WeekCRUD().replace_places(s, places),
|
|
lambda s: WeekCRUD().replace_manual_events(s, events),
|
|
lambda s: SeasonCRUD().upsert_articles(s, articles),
|
|
lambda s: SeasonCRUD().upsert_weeks(s, weeks),
|
|
])
|
|
await DB_SESSION_MNG.stop()
|
|
print(f"region {len(rows)}, ranking {len(ranking)}, sunset_spot {len(spots)}, index {len(indices)}, place {len(places)}, event {len(events)}, article {len(articles)}, season_week {len(weeks)}: {err.name}")
|
|
return 0 if err is ErrorType.SUCCESS else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(asyncio.run(main()))
|