feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)

- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가
- 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시)
- 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리
- 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리
- pytest 66개 (테스트 전용 DB·Redis 사용)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 5.5 committed 2026-10-02 11:32:22 +09:00
1 parent 9cdc0d8fea
commit e134295ce5
135 files changed
+9123

No files matched your search

View File
Whitespace-only changes.
+45
View File
@@ -0,0 +1,45 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, func, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import AirQuality, AirStation, WeatherWarning
class AirCRUD:
async def stations(self, s: AsyncSession) -> list[AirStation]:
return list((await s.scalars(select(AirStation))).all())
async def replace_stations(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
await s.execute(delete(AirStation))
await s.execute(insert(AirStation).values(rows))
async def latest_measured(self, s: AsyncSession) -> Optional[datetime]:
return await s.scalar(select(func.max(AirQuality.measured_at)))
async def upsert_quality(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
stmt = insert(AirQuality).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["station_name"],
set_={k: stmt.excluded[k] for k in ("pm25", "pm10", "grade", "measured_at")},
where=AirQuality.measured_at <= stmt.excluded.measured_at,
))
async def qualities(self, s: AsyncSession, names: list[str]) -> list[AirQuality]:
return list((await s.scalars(select(AirQuality).where(AirQuality.station_name.in_(names)))).all())
class WarningCRUD:
async def replace_all(self, s: AsyncSession, rows: list[dict]) -> None:
await s.execute(delete(WeatherWarning))
if rows:
await s.execute(insert(WeatherWarning).values(rows))
async def all(self, s: AsyncSession) -> list[WeatherWarning]:
return list((await s.scalars(select(WeatherWarning))).all())
+27
View File
@@ -0,0 +1,27 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import or_, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Post
class FeedCRUD:
async def visible(self, s: AsyncSession, now: datetime) -> list[Post]:
stmt = select(Post).where(
Post.deleted.is_(False), Post.published_at <= now, or_(Post.end_at.is_(None), Post.end_at > now)
).order_by(Post.published_at.desc(), Post.position.desc())
return list((await s.scalars(stmt)).all())
async def has_day(self, s: AsyncSession, day: date) -> bool:
return await s.scalar(select(Post.post_id).where(Post.feed_date == day, Post.deleted.is_(False)).limit(1)) is not None
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
if rows:
await s.execute(insert(Post).values(rows).on_conflict_do_nothing())
async def get(self, s: AsyncSession, post_id: int) -> Optional[Post]:
post = await s.get(Post, post_id)
return post if post is not None and not post.deleted else None
+42
View File
@@ -0,0 +1,42 @@
from datetime import date
from sqlalchemy import func, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Holiday, IndexDefinition, IndexScore
class IndexCRUD:
async def definitions(self, s: AsyncSession) -> list[IndexDefinition]:
return list((await s.scalars(select(IndexDefinition).order_by(IndexDefinition.sort_order))).all())
async def upsert_definitions(self, s: AsyncSession, rows: list[dict]) -> None:
stmt = insert(IndexDefinition).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["code"],
set_={k: stmt.excluded[k] for k in rows[0] if k != "code"},
))
async def scores(self, s: AsyncSession, region_code: str, since: date, until: date) -> list[IndexScore]:
stmt = select(IndexScore).where(
IndexScore.region_code == region_code, IndexScore.score_date >= since, IndexScore.score_date <= until
)
return list((await s.scalars(stmt)).all())
async def last_computed(self, s: AsyncSession, region_code: str, day: date):
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
return await s.scalar(stmt)
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
stmt = insert(IndexScore).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["region_code", "score_date", "index_id"],
set_={k: stmt.excluded[k] for k in rows[0] if k not in ("region_code", "score_date", "index_id")},
))
async def holidays(self, s: AsyncSession, since: date, until: date) -> set[date]:
stmt = select(Holiday.holiday_date).where(Holiday.holiday_date >= since, Holiday.holiday_date <= until)
return set((await s.scalars(stmt)).all())
+81
View File
@@ -0,0 +1,81 @@
import uuid
from typing import Optional
from sqlalchemy import delete, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User
class ReactionCRUD:
async def toggle_post_like(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, on: bool) -> int:
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
if on:
res = await s.execute(insert(PostLike).values(post_id=post_id, user_id=user_id).on_conflict_do_nothing().returning(PostLike.post_id))
else:
res = await s.execute(delete(PostLike).where(PostLike.post_id == post_id, PostLike.user_id == user_id).returning(PostLike.post_id))
if res.first() is not None:
await s.execute(update(Post).where(Post.post_id == post_id).values(like_count=Post.like_count + (1 if on else -1)))
return await s.scalar(select(Post.like_count).where(Post.post_id == post_id))
async def toggle_post_save(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, on: bool) -> None:
if on:
await s.execute(insert(PostSave).values(post_id=post_id, user_id=user_id).on_conflict_do_nothing())
else:
await s.execute(delete(PostSave).where(PostSave.post_id == post_id, PostSave.user_id == user_id))
async def counts(self, s: AsyncSession, post_ids: list[int]) -> dict[int, tuple[int, int]]:
rows = await s.execute(select(Post.post_id, Post.like_count, Post.comment_count).where(Post.post_id.in_(post_ids)))
return {pid: (likes, comments) for pid, likes, comments in rows.all()}
async def my_marks(self, s: AsyncSession, user_id: uuid.UUID, post_ids: list[int]) -> tuple[set[int], set[int]]:
liked = set((await s.scalars(select(PostLike.post_id).where(PostLike.user_id == user_id, PostLike.post_id.in_(post_ids)))).all())
saved = set((await s.scalars(select(PostSave.post_id).where(PostSave.user_id == user_id, PostSave.post_id.in_(post_ids)))).all())
return liked, saved
async def saved_posts(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Post, PostSave]]:
stmt = select(Post, PostSave).join(PostSave, PostSave.post_id == Post.post_id).where(PostSave.user_id == user_id, Post.deleted.is_(False))
if cursor is not None:
stmt = stmt.where(Post.post_id < cursor)
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, str]]:
stmt = select(Comment, User.nickname).join(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
if cursor is not None:
stmt = stmt.where(Comment.comment_id > cursor)
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
async def liked_comments(self, s: AsyncSession, user_id: uuid.UUID, comment_ids: list[int]) -> set[int]:
stmt = select(CommentLike.comment_id).where(CommentLike.user_id == user_id, CommentLike.comment_id.in_(comment_ids))
return set((await s.scalars(stmt)).all())
async def add_comment(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, body: str) -> Comment:
c = Comment(post_id=post_id, user_id=user_id, body=body)
s.add(c)
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + 1))
await s.flush()
return c
async def delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool:
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, Comment.user_id == user_id, Comment.deleted.is_(False))
.values(deleted=True).returning(Comment.post_id)
)
post_id = res.scalar()
if post_id is None:
return False
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
return True
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, on: bool) -> Optional[int]:
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
if exists is None:
return None
if on:
res = await s.execute(insert(CommentLike).values(comment_id=comment_id, user_id=user_id).on_conflict_do_nothing().returning(CommentLike.comment_id))
else:
res = await s.execute(delete(CommentLike).where(CommentLike.comment_id == comment_id, CommentLike.user_id == user_id).returning(CommentLike.comment_id))
if res.first() is not None:
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
+27
View File
@@ -0,0 +1,27 @@
from typing import Optional
from sqlalchemy import or_, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Region
class RegionCRUD:
async def search(self, s: AsyncSession, q: Optional[str] = None) -> list[Region]:
stmt = select(Region).order_by(Region.code)
if q:
stmt = stmt.where(or_(Region.name.contains(q), Region.short_name.contains(q)))
return list((await s.scalars(stmt)).all())
async def get(self, s: AsyncSession, code: str) -> Optional[Region]:
return await s.get(Region, code)
async def upsert_many(self, s: AsyncSession, rows: list[dict]) -> None:
stmt = insert(Region).values(rows)
keep = {"is_ranking_spot", "ranking_note"}
stmt = stmt.on_conflict_do_update(
index_elements=[Region.code],
set_={c.name: stmt.excluded[c.name] for c in Region.__table__.columns if c.name != "code" and c.name not in keep},
)
await s.execute(stmt)
+48
View File
@@ -0,0 +1,48 @@
from datetime import date
from typing import Optional
from sqlalchemy import and_, func, or_, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Article, SeasonWeek, SolarTerm
class SeasonCRUD:
async def terms(self, s: AsyncSession, since: date, until: date) -> list[SolarTerm]:
stmt = select(SolarTerm).where(SolarTerm.term_date >= since, SolarTerm.term_date <= until).order_by(SolarTerm.term_date)
return list((await s.scalars(stmt)).all())
async def term_count(self, s: AsyncSession, year: int) -> int:
return await s.scalar(select(func.count()).select_from(SolarTerm).where(func.extract("year", SolarTerm.term_date) == year))
async def upsert_terms(self, s: AsyncSession, rows: list[dict]) -> None:
if rows:
await s.execute(insert(SolarTerm).values(rows).on_conflict_do_nothing(index_elements=["term_date"]))
async def week(self, s: AsyncSession, year: int, week: int) -> Optional[SeasonWeek]:
return await s.get(SeasonWeek, (year, week))
async def upsert_weeks(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
stmt = insert(SeasonWeek).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["year", "week"], set_={k: stmt.excluded[k] for k in ("headline", "poem_lines", "author")},
))
async def articles(self, s: AsyncSession, today: date, category: Optional[int]) -> list[Article]:
visible = and_(or_(Article.show_from.is_(None), Article.show_from <= today), or_(Article.show_until.is_(None), Article.show_until >= today))
stmt = select(Article).where(visible)
if category is not None:
stmt = stmt.where(Article.category == category)
return list((await s.scalars(stmt.order_by(Article.sort_order))).all())
async def article(self, s: AsyncSession, article_id: int) -> Optional[Article]:
return await s.get(Article, article_id)
async def upsert_articles(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
stmt = insert(Article).values(rows)
await s.execute(stmt.on_conflict_do_update(index_elements=["code"], set_={k: stmt.excluded[k] for k in rows[0] if k != "code"}))
+48
View File
@@ -0,0 +1,48 @@
from datetime import date, datetime
from sqlalchemy import and_, delete, or_, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import CloudHourly, Region, SkyScore, SunsetSpot
_CHUNK = 2000
class SkyCRUD:
async def upsert_clouds(self, s: AsyncSession, rows: list[dict]) -> None:
for i in range(0, len(rows), _CHUNK):
stmt = insert(CloudHourly).values(rows[i:i + _CHUNK])
await s.execute(stmt.on_conflict_do_update(
index_elements=["lat", "lon", "forecast_at", "model"],
set_={k: stmt.excluded[k] for k in ("cloud_low", "cloud_mid", "cloud_high")},
))
async def clouds_at(self, s: AsyncSession, points: list[tuple[float, float]], at: datetime) -> list[CloudHourly]:
cond = or_(*[and_(CloudHourly.lat == round(lat, 2), CloudHourly.lon == round(lon, 2)) for lat, lon in points])
return list((await s.scalars(select(CloudHourly).where(cond, CloudHourly.forecast_at == at))).all())
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
stmt = insert(SkyScore).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["region_code", "score_date", "sky_type"],
set_={k: stmt.excluded[k] for k in ("score", "grade", "confidence", "best_times", "computed_at")},
))
async def scores(self, s: AsyncSession, region_codes: list[str], since: date) -> list[SkyScore]:
stmt = select(SkyScore).where(SkyScore.region_code.in_(region_codes), SkyScore.score_date >= since)
return list((await s.scalars(stmt.order_by(SkyScore.score_date))).all())
async def spots(self, s: AsyncSession, region_code: str) -> list[SunsetSpot]:
stmt = select(SunsetSpot).where(SunsetSpot.region_code == region_code).order_by(SunsetSpot.sort_order)
return list((await s.scalars(stmt)).all())
async def replace_spots(self, s: AsyncSession, rows: list[dict]) -> None:
await s.execute(delete(SunsetSpot))
if rows:
await s.execute(insert(SunsetSpot).values(rows))
async def ranking_regions(self, s: AsyncSession) -> list[Region]:
return list((await s.scalars(select(Region).where(Region.is_ranking_spot.is_(True)))).all())
+22
View File
@@ -0,0 +1,22 @@
import uuid
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import User
class UserCRUD:
async def by_login_id(self, s: AsyncSession, login_id: str) -> Optional[User]:
return await s.scalar(select(User).where(User.login_id == login_id, User.deleted.is_(False)))
async def get(self, s: AsyncSession, user_id: uuid.UUID) -> Optional[User]:
user = await s.get(User, user_id)
return user if user is not None and not user.deleted else None
async def create(self, s: AsyncSession, login_id: str, password_hash: str, nickname: str) -> User:
user = User(login_id=login_id, password=password_hash, nickname=nickname, provider=1)
s.add(user)
await s.flush()
return user
+46
View File
@@ -0,0 +1,46 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import func, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import SunTime, WeatherDaily, WeatherHourly
def _upsert_newer(model, rows: list[dict], keys: list[str]):
"""같은 키면 더 늦은 발표(issued_at)만 덮어쓴다."""
stmt = insert(model).values(rows)
return stmt.on_conflict_do_update(
index_elements=keys,
set_={c.name: stmt.excluded[c.name] for c in model.__table__.columns if c.name not in keys},
where=model.issued_at <= stmt.excluded.issued_at,
)
class WeatherCRUD:
async def upsert_hourly(self, s: AsyncSession, rows: list[dict]) -> None:
if rows:
await s.execute(_upsert_newer(WeatherHourly, rows, ["region_code", "forecast_at"]))
async def upsert_daily(self, s: AsyncSession, rows: list[dict]) -> None:
if rows:
await s.execute(_upsert_newer(WeatherDaily, rows, ["region_code", "forecast_date"]))
async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]:
return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code))
async def hourly_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[WeatherHourly]:
stmt = (
select(WeatherHourly)
.where(WeatherHourly.region_code == region_code, WeatherHourly.forecast_at >= start, WeatherHourly.forecast_at < end)
.order_by(WeatherHourly.forecast_at)
)
return list((await s.scalars(stmt)).all())
async def get_sun(self, s: AsyncSession, region_code: str, d: date) -> Optional[SunTime]:
return await s.get(SunTime, (region_code, d))
async def upsert_sun(self, s: AsyncSession, row: dict) -> None:
stmt = insert(SunTime).values(row)
await s.execute(stmt.on_conflict_do_nothing(index_elements=["region_code", "sun_date"]))
+54
View File
@@ -0,0 +1,54 @@
from datetime import date
from sqlalchemy import delete, func, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Event, Holiday, Place, WeatherDaily
class WeekCRUD:
async def daily(self, s: AsyncSession, region_code: str, since: date, until: date) -> list[WeatherDaily]:
stmt = select(WeatherDaily).where(
WeatherDaily.region_code == region_code, WeatherDaily.forecast_date >= since, WeatherDaily.forecast_date <= until
)
return list((await s.scalars(stmt.order_by(WeatherDaily.forecast_date))).all())
async def holidays(self, s: AsyncSession, since: date, until: date) -> dict[date, str]:
stmt = select(Holiday).where(Holiday.holiday_date >= since, Holiday.holiday_date <= until)
return {h.holiday_date: h.name for h in (await s.scalars(stmt)).all()}
async def holiday_count(self, s: AsyncSession, year: int) -> int:
stmt = select(func.count()).select_from(Holiday).where(func.extract("year", Holiday.holiday_date) == year)
return await s.scalar(stmt)
async def upsert_holidays(self, s: AsyncSession, rows: list[dict]) -> None:
if rows:
await s.execute(insert(Holiday).values(rows).on_conflict_do_nothing(index_elements=["holiday_date", "name"]))
async def places(self, s: AsyncSession, sido_code: str) -> list[Place]:
stmt = select(Place).where(Place.region_code.startswith(sido_code)).order_by(Place.sort_order)
return list((await s.scalars(stmt)).all())
async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None:
await s.execute(delete(Place))
if rows:
await s.execute(insert(Place).values(rows))
async def events(self, s: AsyncSession, sido_code: str, since: date, until: date) -> list[Event]:
stmt = select(Event).where(Event.sido_code == sido_code, Event.end_date >= since, Event.start_date <= until)
return list((await s.scalars(stmt.order_by(Event.start_date))).all())
async def upsert_events(self, s: AsyncSession, rows: list[dict]) -> None:
if not rows:
return
stmt = insert(Event).values(rows)
await s.execute(stmt.on_conflict_do_update(
index_elements=["source_id"],
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed")},
))
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
await s.execute(delete(Event).where(Event.source_id.is_(None)))
if rows:
await s.execute(insert(Event).values(rows))