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:
1 parent
9cdc0d8fea
commit
e134295ce5
135 files changed
+9123
No files matched your search
@@ -0,0 +1,21 @@
|
||||
# 프론트·백엔드가 이 파일 하나를 같이 쓴다. compose 가 env_file 로 각 서비스에 넣는다.
|
||||
|
||||
# ── 백엔드: 외부 API
|
||||
# 공공데이터포털(data.go.kr) 일반 인증키.
|
||||
DATA_GO_KR_SERVICE_KEY=
|
||||
|
||||
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5440
|
||||
DB_USER=nalssigak
|
||||
DB_PASSWORD=
|
||||
DB_NAME=nalssigak
|
||||
REDIS_HOST=localhost
|
||||
REDIS_PORT=6390
|
||||
# 네이티브로 띄울 때 API 포트 (o2o-site-AEO 가 9800 을 써서 9810)
|
||||
PORT=9810
|
||||
|
||||
# ── 백엔드: 로그인 토큰 서명 키. 비우면 로그인이 동작하지 않는다
|
||||
# 생성: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
JWT_ACCESS_SECRET=
|
||||
JWT_REFRESH_SECRET=
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
# 환경변수: 실제 값(.env)은 커밋하지 않는다. 템플릿(.env.example)만 커밋한다.
|
||||
# 프론트·백엔드가 최상위 .env 하나를 같이 쓴다 (o2o-site-AEO 와 같음).
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Python 바이트코드/캐시
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
|
||||
# 가상환경
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# 생성물: python backend/scripts/export_openapi.py 로 다시 만든다
|
||||
backend/openapi.json
|
||||
@@ -0,0 +1,5 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
docs/
|
||||
tests/
|
||||
Whitespace-only changes.
@@ -0,0 +1,12 @@
|
||||
# web·worker 가 같은 이미지를 쓰고 compose 의 command 로만 갈린다.
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY . .
|
||||
|
||||
EXPOSE 9800
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:9800/healthz', timeout=4).status==200 else 1)"
|
||||
CMD ["python", "web_main.py"]
|
||||
Whitespace-only changes.
@@ -0,0 +1,71 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Depends, Header, HTTPException
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
from crud.user_crud import UserCRUD
|
||||
|
||||
_ALGORITHM = "HS256"
|
||||
|
||||
|
||||
async def hash_password(password: str) -> str:
|
||||
"""bcrypt 는 느려서 이벤트 루프를 막지 않게 스레드로 뺀다."""
|
||||
return (await asyncio.to_thread(bcrypt.hashpw, password.encode(), bcrypt.gensalt())).decode()
|
||||
|
||||
|
||||
async def verify_password(password: str, hashed: str) -> bool:
|
||||
return await asyncio.to_thread(bcrypt.checkpw, password.encode(), hashed.encode())
|
||||
|
||||
|
||||
def issue_tokens(user: User) -> tuple[str, str]:
|
||||
if not settings.jwt_access_secret or not settings.jwt_refresh_secret:
|
||||
raise RuntimeError("JWT_ACCESS_SECRET / JWT_REFRESH_SECRET is empty")
|
||||
now = datetime.now(timezone.utc)
|
||||
access = jwt.encode(
|
||||
{"sub": str(user.user_id), "type": "access", "exp": now + timedelta(minutes=settings.jwt_access_minutes)},
|
||||
settings.jwt_access_secret, algorithm=_ALGORITHM,
|
||||
)
|
||||
refresh = jwt.encode(
|
||||
{"sub": str(user.user_id), "ver": user.token_version, "type": "refresh", "exp": now + timedelta(days=settings.jwt_refresh_days)},
|
||||
settings.jwt_refresh_secret, algorithm=_ALGORITHM,
|
||||
)
|
||||
return access, refresh
|
||||
|
||||
|
||||
def decode(token: str, secret: str, token_type: str) -> Optional[dict]:
|
||||
try:
|
||||
claims = jwt.decode(token, secret, algorithms=[_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
return claims if claims.get("type") == token_type else None
|
||||
|
||||
|
||||
async def _user_from_header(authorization: Optional[str]) -> Optional[User]:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
return None
|
||||
claims = decode(authorization.removeprefix("Bearer "), settings.jwt_access_secret, "access")
|
||||
if claims is None:
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_TOKEN_INVALID.name)
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: UserCRUD().get(s, uuid.UUID(claims["sub"])))
|
||||
if err is not ErrorType.SUCCESS or user is None or user.status != 1:
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_TOKEN_INVALID.name)
|
||||
return user
|
||||
|
||||
|
||||
async def optional_user(authorization: Optional[str] = Header(None)) -> Optional[User]:
|
||||
"""로그인했으면 사용자, 아니면 None. 토큰이 잘못됐으면 401."""
|
||||
return await _user_from_header(authorization)
|
||||
|
||||
|
||||
async def current_user(user: Optional[User] = Depends(optional_user)) -> User:
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_REQUIRED.name)
|
||||
return user
|
||||
Whitespace-only changes.
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncIterator
|
||||
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.logger import LOG
|
||||
|
||||
_RELEASE = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def redis_lock(key: str, ttl_sec: int = 10) -> AsyncIterator[bool]:
|
||||
"""잡았으면 True. 다른 요청이 잡고 있으면 False (기다리지 않음)."""
|
||||
token = uuid.uuid4().hex
|
||||
try:
|
||||
acquired = bool(await REDIS.conn.set(key, token, nx=True, ex=ttl_sec))
|
||||
except RedisError as e:
|
||||
LOG.error(f"[lock] {key} acquire failed: {e}")
|
||||
acquired = True
|
||||
try:
|
||||
yield acquired
|
||||
finally:
|
||||
if acquired:
|
||||
try:
|
||||
await REDIS.conn.eval(_RELEASE, 1, key, token)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[lock] {key} release failed: {e}")
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
from typing import Optional
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
|
||||
class RedisClient:
|
||||
def __init__(self) -> None:
|
||||
self._redis: Optional[Redis] = None
|
||||
|
||||
@property
|
||||
def conn(self) -> Redis:
|
||||
if self._redis is None:
|
||||
self._redis = Redis(host=settings.redis_host, port=settings.redis_port, db=settings.redis_db, decode_responses=True)
|
||||
return self._redis
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._redis is not None:
|
||||
await self._redis.aclose()
|
||||
self._redis = None
|
||||
|
||||
async def ping(self) -> bool:
|
||||
try:
|
||||
return bool(await self.conn.ping())
|
||||
except RedisError as e:
|
||||
LOG.error(f"[redis] ping failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
REDIS = RedisClient()
|
||||
Whitespace-only changes.
@@ -0,0 +1,68 @@
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
SessionFn = Callable[[AsyncSession], Awaitable[Any]]
|
||||
|
||||
|
||||
class DBSessionManager:
|
||||
"""service 는 세션을 직접 열지 않고 실행할 함수를 넘긴다. 세션·트랜잭션은 여기서 책임진다."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._engine: Optional[AsyncEngine] = None
|
||||
self._session: Optional[async_sessionmaker[AsyncSession]] = None
|
||||
|
||||
def start(self) -> None:
|
||||
if self._engine is None:
|
||||
self._engine = create_async_engine(settings.db_url, pool_pre_ping=True)
|
||||
self._session = async_sessionmaker(self._engine, expire_on_commit=False)
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._engine is not None:
|
||||
await self._engine.dispose()
|
||||
self._engine, self._session = None, None
|
||||
|
||||
async def execute_lambda(self, fn: SessionFn) -> tuple[ErrorType, Any]:
|
||||
"""조회 1건."""
|
||||
self.start()
|
||||
try:
|
||||
async with self._session() as s:
|
||||
return ErrorType.SUCCESS, await fn(s)
|
||||
except SQLAlchemyError as e:
|
||||
LOG.error(f"[db] read failed: {e}")
|
||||
return ErrorType.DB_ERROR, None
|
||||
|
||||
async def execute_lambda_run(self, fns: list[SessionFn]) -> ErrorType:
|
||||
"""여러 변경을 한 트랜잭션으로."""
|
||||
self.start()
|
||||
try:
|
||||
async with self._session() as s, s.begin():
|
||||
for fn in fns:
|
||||
await fn(s)
|
||||
return ErrorType.SUCCESS
|
||||
except SQLAlchemyError as e:
|
||||
LOG.error(f"[db] write failed: {e}")
|
||||
return ErrorType.DB_ERROR
|
||||
|
||||
async def execute_lambda_write(self, fn: SessionFn) -> tuple[ErrorType, Any]:
|
||||
"""변경 1건을 트랜잭션으로 실행하고 결과를 돌려준다."""
|
||||
self.start()
|
||||
try:
|
||||
async with self._session() as s, s.begin():
|
||||
return ErrorType.SUCCESS, await fn(s)
|
||||
except SQLAlchemyError as e:
|
||||
LOG.error(f"[db] write failed: {e}")
|
||||
return ErrorType.DB_ERROR, None
|
||||
|
||||
async def ping(self) -> bool:
|
||||
err, _ = await self.execute_lambda(lambda s: s.execute(text("SELECT 1")))
|
||||
return err is ErrorType.SUCCESS
|
||||
|
||||
|
||||
DB_SESSION_MNG = DBSessionManager()
|
||||
Whitespace-only changes.
@@ -0,0 +1,317 @@
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, Integer, Numeric, SmallInteger, String, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class Region(Base):
|
||||
__tablename__ = "region"
|
||||
|
||||
code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(30))
|
||||
short_name: Mapped[str] = mapped_column(String(20))
|
||||
lat: Mapped[Decimal] = mapped_column(Numeric(8, 5))
|
||||
lon: Mapped[Decimal] = mapped_column(Numeric(8, 5))
|
||||
nx: Mapped[int] = mapped_column(SmallInteger)
|
||||
ny: Mapped[int] = mapped_column(SmallInteger)
|
||||
warning_zone_code: Mapped[str] = mapped_column(String(10))
|
||||
mid_land_code: Mapped[str] = mapped_column(String(10))
|
||||
mid_temp_code: Mapped[str] = mapped_column(String(10))
|
||||
is_ranking_spot: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
ranking_note: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
|
||||
|
||||
|
||||
class WeatherHourly(Base):
|
||||
__tablename__ = "weather_hourly"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||
temp_c: Mapped[Decimal] = mapped_column(Numeric(4, 1))
|
||||
feels_c: Mapped[Decimal] = mapped_column(Numeric(4, 1))
|
||||
discomfort_index: Mapped[int] = mapped_column(SmallInteger)
|
||||
sky: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_prob: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_mm: Mapped[Decimal] = mapped_column(Numeric(5, 1))
|
||||
humidity: Mapped[int] = mapped_column(SmallInteger)
|
||||
wind_ms: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
issued_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class WeatherDaily(Base):
|
||||
__tablename__ = "weather_daily"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
forecast_date: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
temp_min_c: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
temp_max_c: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
sky: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_prob: Mapped[int] = mapped_column(SmallInteger)
|
||||
issued_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class SunTime(Base):
|
||||
__tablename__ = "sun_time"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
sun_date: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
sunrise_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
sunset_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
dusk_end_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
sunset_azimuth: Mapped[int] = mapped_column(SmallInteger)
|
||||
|
||||
|
||||
class AirStation(Base):
|
||||
__tablename__ = "air_station"
|
||||
|
||||
station_name: Mapped[str] = mapped_column(String(30), primary_key=True)
|
||||
lat: Mapped[Decimal] = mapped_column(Numeric(8, 5))
|
||||
lon: Mapped[Decimal] = mapped_column(Numeric(8, 5))
|
||||
|
||||
|
||||
class AirQuality(Base):
|
||||
__tablename__ = "air_quality"
|
||||
|
||||
station_name: Mapped[str] = mapped_column(String(30), primary_key=True)
|
||||
pm25: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
pm10: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
grade: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
measured_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class WeatherWarning(Base):
|
||||
__tablename__ = "weather_warning"
|
||||
|
||||
warning_zone_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
warning_type: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
level: Mapped[int] = mapped_column(SmallInteger)
|
||||
|
||||
|
||||
class CloudHourly(Base):
|
||||
__tablename__ = "cloud_hourly"
|
||||
|
||||
lat: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True)
|
||||
lon: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True)
|
||||
forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||
model: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
cloud_low: Mapped[int] = mapped_column(SmallInteger)
|
||||
cloud_mid: Mapped[int] = mapped_column(SmallInteger)
|
||||
cloud_high: Mapped[int] = mapped_column(SmallInteger)
|
||||
|
||||
|
||||
class SkyScore(Base):
|
||||
__tablename__ = "sky_score"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
score_date: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
sky_type: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
score: Mapped[int] = mapped_column(SmallInteger)
|
||||
grade: Mapped[int] = mapped_column(SmallInteger)
|
||||
confidence: Mapped[int] = mapped_column(SmallInteger)
|
||||
best_times: Mapped[list] = mapped_column(JSONB)
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class SunsetSpot(Base):
|
||||
__tablename__ = "sunset_spot"
|
||||
|
||||
spot_id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
name: Mapped[str] = mapped_column(String(40))
|
||||
description: Mapped[str] = mapped_column(String(100))
|
||||
lat: Mapped[Decimal] = mapped_column(Numeric(8, 5))
|
||||
lon: Mapped[Decimal] = mapped_column(Numeric(8, 5))
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
|
||||
|
||||
class IndexDefinition(Base):
|
||||
__tablename__ = "index_definition"
|
||||
|
||||
index_id: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(30), unique=True)
|
||||
name: Mapped[str] = mapped_column(String(20))
|
||||
icon: Mapped[str] = mapped_column(String(30))
|
||||
category: Mapped[int] = mapped_column(SmallInteger)
|
||||
is_fun: Mapped[bool] = mapped_column(Boolean)
|
||||
is_core: Mapped[bool] = mapped_column(Boolean)
|
||||
has_detail: Mapped[bool] = mapped_column(Boolean)
|
||||
description: Mapped[str] = mapped_column(String(100))
|
||||
windows: Mapped[list] = mapped_column(JSONB)
|
||||
weight_temp: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_rain: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_wind: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_humidity: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_air: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_time: Mapped[int] = mapped_column(SmallInteger)
|
||||
factor_rules: Mapped[dict] = mapped_column(JSONB)
|
||||
zero_rules: Mapped[list] = mapped_column(JSONB)
|
||||
limit_description: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
__tablename__ = "index_score"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
score_date: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
index_id: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
score: Mapped[int] = mapped_column(SmallInteger)
|
||||
summary: Mapped[str] = mapped_column(String(100))
|
||||
temp_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
rain_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
wind_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
humidity_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
air_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
time_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class Holiday(Base):
|
||||
__tablename__ = "holiday"
|
||||
|
||||
holiday_date: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(20), primary_key=True)
|
||||
|
||||
|
||||
class Place(Base):
|
||||
__tablename__ = "place"
|
||||
|
||||
place_id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
area: Mapped[str] = mapped_column(String(20))
|
||||
name: Mapped[str] = mapped_column(String(40))
|
||||
is_outdoor: Mapped[bool] = mapped_column(Boolean)
|
||||
icon: Mapped[str] = mapped_column(String(30))
|
||||
reason: Mapped[str] = mapped_column(String(60))
|
||||
best_time: Mapped[str] = mapped_column(String(30))
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
|
||||
|
||||
class Event(Base):
|
||||
__tablename__ = "event"
|
||||
|
||||
event_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
source_id: Mapped[Optional[str]] = mapped_column(String(20), unique=True, nullable=True)
|
||||
sido_code: Mapped[str] = mapped_column(String(2))
|
||||
region_code: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
|
||||
area: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
name: Mapped[str] = mapped_column(String(60))
|
||||
place_name: Mapped[str] = mapped_column(String(60))
|
||||
icon: Mapped[str] = mapped_column(String(30), default="calendar")
|
||||
start_date: Mapped[date] = mapped_column(Date)
|
||||
end_date: Mapped[date] = mapped_column(Date)
|
||||
is_confirmed: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
source_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
|
||||
|
||||
class SolarTerm(Base):
|
||||
__tablename__ = "solar_term"
|
||||
|
||||
term_date: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(10))
|
||||
|
||||
|
||||
class SeasonWeek(Base):
|
||||
__tablename__ = "season_week"
|
||||
|
||||
year: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
week: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
headline: Mapped[str] = mapped_column(String(60))
|
||||
poem_lines: Mapped[list] = mapped_column(JSONB)
|
||||
author: Mapped[str] = mapped_column(String(60))
|
||||
|
||||
|
||||
class Article(Base):
|
||||
__tablename__ = "article"
|
||||
|
||||
article_id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(40), unique=True)
|
||||
category: Mapped[int] = mapped_column(SmallInteger)
|
||||
title: Mapped[str] = mapped_column(String(80))
|
||||
read_minutes: Mapped[int] = mapped_column(SmallInteger)
|
||||
icon: Mapped[str] = mapped_column(String(30))
|
||||
body: Mapped[list] = mapped_column(JSONB)
|
||||
show_from: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
show_until: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
|
||||
|
||||
class Post(Base):
|
||||
__tablename__ = "post"
|
||||
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
feed_date: Mapped[date] = mapped_column(Date)
|
||||
position: Mapped[int] = mapped_column(SmallInteger)
|
||||
post_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
ref_type: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
ref_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
index_rank: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
comment_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
published_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
end_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
provider: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
login_id: Mapped[str] = mapped_column(String(64))
|
||||
password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
provider_uid: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
nickname: Mapped[str] = mapped_column(String(30))
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class PostLike(Base):
|
||||
__tablename__ = "post_like"
|
||||
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PostSave(Base):
|
||||
__tablename__ = "post_save"
|
||||
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class Comment(Base):
|
||||
__tablename__ = "comment"
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
post_id: Mapped[int] = mapped_column(BigInteger)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
body: Mapped[str] = mapped_column(String(60))
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class CommentLike(Base):
|
||||
__tablename__ = "comment_like"
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -0,0 +1,132 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class CodeEnum(int, Enum):
|
||||
"""정수 코드값 enum. 쿼리 문자열("2")도 받는다. OpenAPI 에 이름(x-enum-varnames)을 실어 프론트가 이름 있는 enum 을 만들게 한다."""
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_json_schema__(cls, core_schema, handler):
|
||||
json_schema = handler(core_schema)
|
||||
json_schema = handler.resolve_ref_schema(json_schema)
|
||||
json_schema["x-enum-varnames"] = [m.name for m in cls]
|
||||
return json_schema
|
||||
|
||||
|
||||
class ErrorType(Enum):
|
||||
SUCCESS = 0
|
||||
DB_ERROR = 1001
|
||||
CACHE_ERROR = 1002
|
||||
EXTERNAL_API_ERROR = 2001
|
||||
NOT_FOUND = 3001
|
||||
INVALID_INPUT = 3002
|
||||
AUTH_REQUIRED = 4001
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
AUTH_TOKEN_INVALID = 4004
|
||||
|
||||
|
||||
class Sky(CodeEnum):
|
||||
CLEAR = 1
|
||||
PARTLY = 2
|
||||
CLOUDY = 3
|
||||
|
||||
|
||||
class RainType(CodeEnum):
|
||||
NONE = 1
|
||||
RAIN = 2
|
||||
SLEET = 3
|
||||
SNOW = 4
|
||||
SHOWER = 5
|
||||
|
||||
|
||||
class SlotTone(CodeEnum):
|
||||
DAY = 1
|
||||
NIGHT = 2
|
||||
SUNSET = 3
|
||||
|
||||
|
||||
class AirGrade(CodeEnum):
|
||||
GOOD = 1
|
||||
NORMAL = 2
|
||||
BAD = 3
|
||||
VERY_BAD = 4
|
||||
|
||||
|
||||
class WarningType(CodeEnum):
|
||||
WIND = 1
|
||||
RAIN = 2
|
||||
COLD = 3
|
||||
DRY = 4
|
||||
STORM_SURGE = 5
|
||||
HIGH_SEAS = 6
|
||||
TYPHOON = 7
|
||||
SNOW = 8
|
||||
YELLOW_DUST = 9
|
||||
HEAT = 12
|
||||
TROPICAL_NIGHT = 13
|
||||
|
||||
|
||||
class WarningLevel(CodeEnum):
|
||||
ADVISORY = 1
|
||||
WARNING = 2
|
||||
SEVERE = 3
|
||||
|
||||
|
||||
class CloudModel(CodeEnum):
|
||||
ECMWF = 1
|
||||
GFS = 2
|
||||
JMA = 3
|
||||
ICON = 4
|
||||
|
||||
|
||||
class SkyType(CodeEnum):
|
||||
SUNSET = 1
|
||||
SUNRISE = 2
|
||||
|
||||
|
||||
class SkyGrade(CodeEnum):
|
||||
GRAY = 1
|
||||
SOFT = 2
|
||||
GLOW = 3
|
||||
RED = 4
|
||||
|
||||
|
||||
class Confidence(CodeEnum):
|
||||
HIGH = 1
|
||||
NORMAL = 2
|
||||
LOW = 3
|
||||
|
||||
|
||||
class IndexCategory(CodeEnum):
|
||||
OUTSIDE = 1
|
||||
FOOD = 2
|
||||
HOME = 3
|
||||
LIFE = 4
|
||||
|
||||
|
||||
class ArticleCategory(CodeEnum):
|
||||
SEASON = 1
|
||||
TIP = 2
|
||||
GAK = 3
|
||||
|
||||
|
||||
class PostType(CodeEnum):
|
||||
WEATHER = 1
|
||||
GAK = 2
|
||||
SUNSET = 3
|
||||
SEASON = 4
|
||||
EVENT = 5
|
||||
TIP = 6
|
||||
WEEK = 7
|
||||
|
||||
|
||||
class RefType(CodeEnum):
|
||||
NONE = 1
|
||||
INDEX = 2
|
||||
ARTICLE = 3
|
||||
EVENT = 4
|
||||
|
||||
|
||||
class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
@@ -0,0 +1,6 @@
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
LOG = logging.getLogger("nalssigak")
|
||||
# httpx 는 요청 URL(서비스 키 포함)을 INFO 로 찍어서 끈다.
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
Whitespace-only changes.
@@ -0,0 +1,6 @@
|
||||
from common.enums import ErrorType
|
||||
from common.models.gmodel import ErrorInfo
|
||||
|
||||
|
||||
def error_info(err: ErrorType) -> ErrorInfo:
|
||||
return ErrorInfo(success=err is ErrorType.SUCCESS, code=err.value, desc=err.name)
|
||||
@@ -0,0 +1,24 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from common.enums import ErrorType
|
||||
|
||||
|
||||
class ErrorInfo(BaseModel):
|
||||
success: bool = True
|
||||
code: int = ErrorType.SUCCESS.value
|
||||
desc: str = ErrorType.SUCCESS.name
|
||||
|
||||
|
||||
class WebPacketProtocol(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class Req_WebPacketProtocol(WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_WebPacketProtocol(WebPacketProtocol):
|
||||
result: ErrorInfo = Field(default_factory=ErrorInfo)
|
||||
msg: Optional[str] = None
|
||||
Whitespace-only changes.
@@ -0,0 +1,19 @@
|
||||
import math
|
||||
|
||||
_EARTH_RADIUS_KM = 6371.0088
|
||||
|
||||
|
||||
def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||
dp, dl = p2 - p1, math.radians(lon2 - lon1)
|
||||
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
||||
return 2 * _EARTH_RADIUS_KM * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def destination(lat: float, lon: float, bearing_deg: float, km: float) -> tuple[float, float]:
|
||||
"""출발점에서 방위각 방향으로 km 떨어진 지점."""
|
||||
d = km / _EARTH_RADIUS_KM
|
||||
p1, l1, b = math.radians(lat), math.radians(lon), math.radians(bearing_deg)
|
||||
p2 = math.asin(math.sin(p1) * math.cos(d) + math.cos(p1) * math.sin(d) * math.cos(b))
|
||||
l2 = l1 + math.atan2(math.sin(b) * math.sin(d) * math.cos(p1), math.cos(d) - math.sin(p1) * math.sin(p2))
|
||||
return math.degrees(p2), (math.degrees(l2) + 540) % 360 - 180
|
||||
@@ -0,0 +1,39 @@
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
KST = timezone(timedelta(hours=9))
|
||||
|
||||
VILAGE_BASE_HOURS = (2, 5, 8, 11, 14, 17, 20, 23)
|
||||
VILAGE_DELAY = timedelta(minutes=10)
|
||||
ULTRA_DELAY = timedelta(minutes=15)
|
||||
|
||||
|
||||
def now_kst() -> datetime:
|
||||
return datetime.now(KST)
|
||||
|
||||
|
||||
def kst_midnight(d: date) -> datetime:
|
||||
return datetime.combine(d, time(0), tzinfo=KST)
|
||||
|
||||
|
||||
def latest_vilage_base(now: datetime) -> datetime:
|
||||
"""지금 받을 수 있는 가장 최근 단기예보 발표 시각 (발표 10분 뒤부터 제공)."""
|
||||
now = now.astimezone(KST)
|
||||
for day_offset in (0, 1):
|
||||
d = (now - timedelta(days=day_offset)).date()
|
||||
for h in reversed(VILAGE_BASE_HOURS):
|
||||
base = datetime.combine(d, time(h), tzinfo=KST)
|
||||
if base + VILAGE_DELAY <= now:
|
||||
return base
|
||||
raise AssertionError("unreachable")
|
||||
|
||||
|
||||
def next_vilage_available(now: datetime) -> datetime:
|
||||
"""다음 단기예보가 제공되는 시각."""
|
||||
return latest_vilage_base(now) + timedelta(hours=3) + VILAGE_DELAY
|
||||
|
||||
|
||||
def latest_ultra_base(now: datetime) -> datetime:
|
||||
"""지금 받을 수 있는 가장 최근 초단기예보 발표 시각 (매시 30분 발표, 45분부터 제공)."""
|
||||
now = now.astimezone(KST)
|
||||
base = now.replace(minute=30, second=0, microsecond=0)
|
||||
return base if base + ULTRA_DELAY <= now else base - timedelta(hours=1)
|
||||
@@ -0,0 +1,19 @@
|
||||
def hour_label(h: int) -> str:
|
||||
if h == 0:
|
||||
return "자정"
|
||||
if h < 12:
|
||||
return f"오전 {h}시"
|
||||
if h == 12:
|
||||
return "낮 12시"
|
||||
return f"오후 {h - 12}시"
|
||||
|
||||
|
||||
def ieyo(word: str) -> str:
|
||||
"""받침이 있으면 '이에요', 없으면 '예요'."""
|
||||
last = word[-1] if word else ""
|
||||
has_final = "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0
|
||||
return f"{word}이에요" if has_final else f"{word}예요"
|
||||
|
||||
|
||||
def month_day(d) -> str:
|
||||
return f"{d.month}월 {d.day}일"
|
||||
Whitespace-only changes.
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
from urllib.parse import unquote
|
||||
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# 프론트·백엔드가 저장소 최상위 .env 하나를 같이 쓴다.
|
||||
_ROOT_ENV = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), ".env")
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=_ROOT_ENV, env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
app_env: str = "local"
|
||||
server_name: str = "nalssigak"
|
||||
port: int = 9810
|
||||
process_count: int = 1
|
||||
|
||||
db_host: str = "localhost"
|
||||
db_port: int = 5440
|
||||
db_user: str = "nalssigak"
|
||||
db_password: str = ""
|
||||
db_name: str = "nalssigak"
|
||||
|
||||
redis_host: str = "localhost"
|
||||
redis_port: int = 6390
|
||||
redis_db: int = 0
|
||||
|
||||
data_go_kr_service_key: str = ""
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
jwt_access_minutes: int = 60
|
||||
jwt_refresh_days: int = 30
|
||||
|
||||
@field_validator("data_go_kr_service_key")
|
||||
@classmethod
|
||||
def _decode_service_key(cls, v: str) -> str:
|
||||
"""인코딩 키를 넣어도 디코딩해 둔다. httpx 가 다시 인코딩하므로 이중 인코딩을 막는다."""
|
||||
return unquote(v) if "%" in v else v
|
||||
|
||||
@property
|
||||
def db_url(self) -> str:
|
||||
return f"postgresql+asyncpg://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
Whitespace-only changes.
@@ -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())
|
||||
@@ -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
|
||||
@@ -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())
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
@@ -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"}))
|
||||
@@ -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())
|
||||
@@ -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
|
||||
@@ -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"]))
|
||||
@@ -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))
|
||||
@@ -0,0 +1,31 @@
|
||||
# 백엔드 문서
|
||||
|
||||
| 문서 | 내용 | 아티팩트 |
|
||||
|---|---|---|
|
||||
| `data-pipeline.md` (`.html` 은 같은 내용) | 외부 API를 언제 받아 어디에 저장·캐시하는지, 피드 칸, 하루 1번 스케줄, 테스트 DB | https://claude.ai/artifact/A4cE22L5aPnMfU53mKCSps |
|
||||
| `api.html` | API 목록, 응답 예시, 프론트 연결(Hey API) | https://claude.ai/artifact/LjVYpLzomBTrkMxjDvAoDD |
|
||||
| `index-draft.html` | 활동 지수 23개 기준 초안 (실제 값은 `seed/index_definition.json`) | https://claude.ai/artifact/RrgaKozLCycwduymWPXz4s |
|
||||
| `api-codegen.html` | 프론트 코드 생성 도구 비교 (Hey API 로 결정) | https://claude.ai/artifact/FPuknSnajrmxTM7hEpPKek |
|
||||
| `aeo-backend-report.html` | 따라 한 o2o-site-AEO 백엔드 구조 | https://claude.ai/artifact/At64pyzXkwuczfJn4L3GDf |
|
||||
|
||||
## 실행
|
||||
|
||||
```bash
|
||||
docker compose up -d --build backend worker postgres redis frontend # API :9810, 프론트 :8080
|
||||
cd backend && python scripts/load_seed.py # 시드 넣기 (구·지수·명소·글)
|
||||
cd backend && .venv/bin/python -m pytest -q # 테스트 (nalssigak_test DB 를 새로 만듦)
|
||||
cd frontend && npm run api # 백엔드 API 바뀌면 프론트 코드 다시 생성
|
||||
```
|
||||
|
||||
## 시드 (사람이 채우는 콘텐츠)
|
||||
|
||||
| 파일 | 내용 |
|
||||
|---|---|
|
||||
| `seed/region.csv` | 시군구 256곳, 기상청 칸·특보·중기 구역 코드 |
|
||||
| `seed/index_definition.json` | 지수 23개 정의·비중·0점 조건 |
|
||||
| `seed/ranking_spot.csv` | 전국 노을 순위 대표 30곳 |
|
||||
| `seed/sunset_spot.csv` | 노을 명소 (지금 마포구 3곳) |
|
||||
| `seed/place.csv` | 데이트 명소 (지금 서울 10곳) |
|
||||
| `seed/event.csv` | TourAPI 에 없는 행사 (지금 비어 있음) |
|
||||
| `seed/article.json` | 계절 소식·날씨 상식·각 원리 글 |
|
||||
| `seed/season_week.json` | 주차별 시 (저작권 만료 작품만, 지금 40주차 1개) |
|
||||
@@ -0,0 +1,146 @@
|
||||
<title>AEO 백엔드 구조 보고서</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&family=IBM+Plex+Mono:wght@400&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: 요약 → 구조 → 패턴 → DB → 인증 → 외부 API → 잡·스케줄 → 도커 → 날씨각에 가져올 것 */
|
||||
:root{
|
||||
--bg:#f4f7f6; --fg:#1b2624; --muted:#4a5955; --line:#d3dedb; --soft:#e7efed; --accent:#17614f; --warn:#8f3c17;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#111917;--fg:#e2ebe8;--muted:#93a6a1;--line:#2a3734;--soft:#18221f;--accent:#5cc2ab;--warn:#f0956a;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#111917;--fg:#e2ebe8;--muted:#93a6a1;--line:#2a3734;--soft:#18221f;--accent:#5cc2ab;--warn:#f0956a;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14.5px;line-height:1.65}
|
||||
main{max-width:980px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:30px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:21px;margin:0 0 10px;text-wrap:balance}
|
||||
p,li{max-width:72ch}
|
||||
p{margin:0 0 8px}
|
||||
ul{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:4px}
|
||||
.sub{color:var(--muted)}
|
||||
code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:1px 5px;border-radius:3px}
|
||||
pre{font-family:var(--mono);font-size:12.5px;background:var(--soft);border:1px solid var(--line);border-radius:6px;padding:12px 14px;overflow-x:auto;margin:0}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:640px}
|
||||
th,td{text-align:left;vertical-align:top;padding:8px 10px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
.k{color:var(--accent);font-weight:600}
|
||||
.w{color:var(--warn);font-weight:600}
|
||||
</style>
|
||||
<main>
|
||||
<header>
|
||||
<h1>o2o-site-AEO 백엔드 구조 보고서</h1>
|
||||
<p class="sub">대상: <code>/Users/minachoi/projects/o2o-site-AEO/solution/backend</code> · 2026-10-01 · 날씨각 백엔드가 따라 할 구조를 정리한 문서</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>한 줄 요약</h2>
|
||||
<p>상호명 하나로 소상공인 홈페이지를 만들어 주는 서비스의 API 서버입니다. FastAPI + SQLAlchemy(async) + PostgreSQL 구성이고, <span class="k">router → service → crud</span> 3층 구조입니다. 오래 걸리는 일은 PostgreSQL을 큐로 쓰는 worker가 따로 처리합니다. 다른 사내 프로젝트(negodata)의 뼈대를 옮겨 온 것이라 규칙이 엄격하게 정해져 있습니다.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>폴더 구조와 실행</h2>
|
||||
<pre>solution/backend/
|
||||
├── web_main.py API 서버 (:9800, uvicorn). RELOAD=1 이면 자동 재시작
|
||||
├── worker_main.py 잡 러너. 종료 신호를 받으면 하던 잡은 끝내고 멈춤
|
||||
├── config/ APP_ENV 별 설정 + .env (pydantic-settings)
|
||||
├── common/
|
||||
│ ├── enums.py 결과 코드(ErrorType), 코드값 enum(CodeEnum)
|
||||
│ ├── database/ DB 세션 매니저, ORM 모델
|
||||
│ ├── models/ 패킷 베이스(WebPacketProtocol)
|
||||
│ └── utils/ 시간·거리·메모리 캐시·호출 제한
|
||||
├── router/v1/<도메인>/ 라우터 + protocol.py(요청·응답 모양)
|
||||
├── services/ 비즈니스 로직, external/(외부 API 클라이언트)
|
||||
├── crud/ DB 조회·변경 (인터페이스 + 구현)
|
||||
├── scheduler/ APScheduler 크론 (언제) / jobs.py (무엇을)
|
||||
├── worker/ 잡 핸들러, 러너, LISTEN/NOTIFY
|
||||
├── scripts/ 마이그레이션, OpenAPI 추출 등
|
||||
└── tests/ pytest (테스트 DB 자동 생성·삭제)
|
||||
postgres-init/init-data/init.sql 전체 DDL 한 벌
|
||||
postgres-init/migrations/NNNN_*.sql 이미 있는 DB 를 따라오게 하는 변경분</pre>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>핵심 패턴</h2>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>패턴</th><th>내용</th></tr>
|
||||
<tr><td>3층 구조</td><td>router(요청 받기) → service(로직) → crud(쿼리). service 는 <code>Depends()</code> 로 crud 를 주입받습니다.</td></tr>
|
||||
<tr><td>DB 세션 매니저</td><td>service 가 세션을 직접 열지 않고, 실행할 함수(람다)를 매니저에 넘깁니다. 조회용·변경용 엔진이 따로 있고, 여러 변경은 한 트랜잭션으로 묶입니다 (<code>execute_lambda</code>, <code>execute_lambda_run</code>).</td></tr>
|
||||
<tr><td>요청·응답 규약</td><td>모든 패킷은 <code>WebPacketProtocol</code> 상속, 이름은 <code>Req_*</code> / <code>Res_*</code>. 응답에는 항상 <code>result: ErrorInfo</code> 가 들어갑니다. 라우터마다 <code>protocol.py</code> 한 개를 둡니다.</td></tr>
|
||||
<tr><td>응답 정리</td><td><code>RemoveNoneResponse</code> 가 응답의 None 필드를 지웁니다.</td></tr>
|
||||
<tr><td>코드값</td><td>상태·종류는 DB 에 SMALLINT 로 저장하고 앱의 <code>CodeEnum</code> 으로 이름을 붙입니다. OpenAPI 에 enum 이름을 실어 프론트(orval)가 이름 있는 enum 을 만듭니다.</td></tr>
|
||||
<tr><td>프론트 타입 생성</td><td><code>python scripts/export_openapi.py</code> 로 서버 없이 <code>openapi.json</code> 을 뽑고, 프론트의 orval 이 이 파일로 TypeScript 타입과 호출 함수를 만듭니다.</td></tr>
|
||||
<tr><td>전부 비동기</td><td>async/await, SQLAlchemy async + asyncpg. 무거운 계산(bcrypt)은 <code>asyncio.to_thread</code> 로 뺍니다.</td></tr>
|
||||
</table></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>DB 규칙</h2>
|
||||
<ul>
|
||||
<li><code>init.sql</code> 한 벌이 최신 스키마이고, DB 를 처음 만들 때만 돕니다. 이미 있는 DB 는 <code>migrations/NNNN_*.sql</code> 을 <code>scripts/migrate.py</code> 로 적용합니다. 그래서 표를 고칠 때는 <span class="w">둘 다 고쳐야 합니다.</span></li>
|
||||
<li>FK 제약을 걸지 않습니다. 관계 컬럼만 두고, 무결성은 앱에서 챙깁니다.</li>
|
||||
<li>코드값은 SMALLINT(1부터)이고, CHECK 제약은 두지 않습니다.</li>
|
||||
<li>삭제는 <code>deleted</code> 컬럼으로 표시만 하고, 유니크는 부분 인덱스로 겁니다.</li>
|
||||
<li>시각은 TIMESTAMPTZ 로, UTC 로 저장합니다.</li>
|
||||
<li>모든 컬럼 옆에 주석으로 이유를 적습니다. 특히 사고가 났던 지점은 ★로 표시합니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>인증</h2>
|
||||
<ul>
|
||||
<li><b>로그인 방식:</b> 아이디·비밀번호(bcrypt)와 구글 OAuth 두 가지입니다. <span class="w">카카오·네이버 로그인은 없습니다.</span> 저장소의 <code>kakao.py</code>, <code>naver.py</code>는 로그인이 아니라 장소 검색용 API입니다.</li>
|
||||
<li><b>토큰:</b> JWT access/refresh를 씁니다. <code>users.token_version</code>을 올리면 그 전에 발급된 refresh 토큰이 모두 무효가 됩니다.</li>
|
||||
<li><b>권한 검사:</b> <code>Depends(IsValidAccessToken)</code>, <code>RequireOwner</code>, <code>RequireDeveloper</code>로 합니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>외부 API 클라이언트 (<code>services/external/</code>)</h2>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>파일</th><th>하는 일</th><th>날씨각 재사용</th></tr>
|
||||
<tr><td><code>tour_api.py</code></td><td>한국관광공사 TourAPI. 주변 관광지, <b>시도별 축제</b>(<code>fetch_festivals_in_sido</code>)</td><td class="k">행사 데이터 출처로 그대로 참고 가능</td></tr>
|
||||
<tr><td><code>open_meteo.py</code></td><td>Open-Meteo 현재 날씨만 (39줄)</td><td>층별 구름·시간별은 새로 짜야 함</td></tr>
|
||||
<tr><td><code>kakao.py</code> · <code>naver.py</code></td><td>로컬 검색으로 같은 업소인지 확인</td><td>로그인과 무관</td></tr>
|
||||
<tr><td><code>google_identity.py</code></td><td>구글 로그인 토큰 검증</td><td>카카오·네이버 로그인 짤 때 구조 참고</td></tr>
|
||||
</table></div>
|
||||
<p style="margin-top:8px">공통 방식은 이렇습니다. 키가 없으면 <code>*NotConfigured</code>, 호출이 실패하면 <code>*RequestFailed</code> 예외를 냅니다. httpx 클라이언트는 <code>make_client()</code>로 만들고, 받은 값은 <code>_normalize()</code>로 우리 형식에 맞게 바꿉니다.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>잡 큐와 스케줄러</h2>
|
||||
<ul>
|
||||
<li><b>잡 큐:</b> PostgreSQL <code>jobs</code> 표를 큐로 씁니다. 원자적으로 잡을 집어 가고(claim), 임대 시간(lease)을 두며, 여러 번 실패한 잡은 dead-letter로 보냅니다. API는 잡을 넣고 바로 <code>job_id</code>를 돌려주고, 프론트는 <code>GET /v1/job/{id}</code>로 진행 상황을 폴링합니다.</li>
|
||||
<li><b>worker:</b> LISTEN/NOTIFY로 새 잡을 바로 알아채고, 처리 중에 죽은 잡은 reaper가 회수합니다.</li>
|
||||
<li><b>스케줄러:</b> APScheduler를 <span class="w">worker가 아니라 API 프로세스</span> 안에서 <code>SCHEDULER_ENABLED=1</code>일 때만 켭니다. 시간대는 Asia/Seoul이고, 각 잡에 <code>max_instances=1</code>, <code>coalesce=True</code>를 줍니다.</li>
|
||||
<li><b>캐시:</b> Redis 없이 프로세스 메모리 TTL 캐시(<code>ttl_cache.py</code>)와 IP 단위 호출 제한(<code>rate_limit.py</code>)만 씁니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>도커</h2>
|
||||
<ul>
|
||||
<li>API, 내부 API, worker가 <b>같은 이미지</b>를 쓰고 <code>command</code>만 다릅니다. worker는 Node 렌더러 때문에 이미지를 따로 만듭니다.</li>
|
||||
<li>베이스는 <code>python:3.12-slim</code>이고, requirements를 먼저 설치해서 빌드 캐시를 활용합니다.</li>
|
||||
<li>시크릿은 이미지에 굽지 않고 compose 환경변수로 넣습니다.</li>
|
||||
<li>API에는 <code>/healthz</code> HEALTHCHECK를 두고, worker는 포트가 없어 끕니다.</li>
|
||||
<li>메인 PostgreSQL은 compose에 없어서 외부 DB를 쓰는 것으로 보입니다. compose 안의 pgvector·Redis는 별도 ontology 서비스용입니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>날씨각에 가져올 것 / 다르게 할 것</h2>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>항목</th><th>AEO</th><th>날씨각</th></tr>
|
||||
<tr><td>3층 구조, 세션 매니저, Req/Res 규약, CodeEnum</td><td>있음</td><td class="k">그대로</td></tr>
|
||||
<tr><td>init.sql + migrations</td><td>저장소 루트 <code>postgres-init/</code></td><td>요청대로 <code>backend/postgres-init/</code>에 둠</td></tr>
|
||||
<tr><td>OpenAPI → orval</td><td>있음</td><td class="k">그대로 (3단계에서 설명)</td></tr>
|
||||
<tr><td>캐시</td><td>메모리 TTL</td><td>Redis 7 (화면 완성본, 초단기예보, 잠금)</td></tr>
|
||||
<tr><td>정기 수집</td><td>API 프로세스 안 APScheduler</td><td>worker 안에서 돌리는 걸 제안 (API를 여러 개 띄워도 중복 실행 없음)</td></tr>
|
||||
<tr><td>잡 큐</td><td>PostgreSQL 큐 (수집·빌드가 몇 분)</td><td>필요 없음. 날씨 호출은 몇 초 안에 끝나서 스케줄러로 충분</td></tr>
|
||||
<tr><td>로그인</td><td>아이디·비번 + 구글</td><td>카카오 + 네이버 OAuth를 새로 작성</td></tr>
|
||||
<tr><td>내부(어드민) API</td><td>:9801 별도 진입점</td><td>지금은 없음</td></tr>
|
||||
</table></div>
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,77 @@
|
||||
<title>API 연결 도구 비교</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: 결론 → 비교표 → 왜 orval 이었나 → 바꾸면 드는 일 → 출처 */
|
||||
:root{
|
||||
--bg:#f6f7fa; --fg:#1d2330; --muted:#404a5b; --line:#d6dbe5; --soft:#eaeef5; --accent:#2b56a0; --good:#1d6b46; --warn:#8f3c17;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#12161e;--fg:#e4e8f0;--muted:#a9b3c4;--line:#2b3342;--soft:#19202b;--accent:#93b5ef;--good:#7fd8ab;--warn:#f0a07a;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#12161e;--fg:#e4e8f0;--muted:#a9b3c4;--line:#2b3342;--soft:#19202b;--accent:#93b5ef;--good:#7fd8ab;--warn:#f0a07a;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14.5px;line-height:1.65}
|
||||
main{max-width:1040px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:30px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:21px;margin:0 0 10px;text-wrap:balance}
|
||||
p,li{max-width:76ch}
|
||||
p{margin:0 0 8px}
|
||||
ul{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:5px}
|
||||
.sub{color:var(--muted)}
|
||||
code{font-size:12.5px;background:var(--soft);padding:2px 6px;border-radius:3px}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:820px}
|
||||
th,td{text-align:left;vertical-align:top;padding:9px 11px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
.g{color:var(--good);font-weight:600}.w{color:var(--warn);font-weight:600}
|
||||
</style>
|
||||
<main>
|
||||
<header>
|
||||
<h1>프론트↔백엔드 API 연결 도구 비교</h1>
|
||||
<p class="sub">2026-10-02 · FastAPI가 만드는 OpenAPI 스펙으로 TypeScript 타입·호출 코드를 자동 생성하는 도구</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>결론</h2>
|
||||
<ul>
|
||||
<li><b>2026-10-02 Hey API 로 바꿨습니다.</b> 아래는 바꾸기 전에 비교한 내용입니다.</li>
|
||||
<li><b>2026년 추세의 1순위는 Hey API</b>(<code>@hey-api/openapi-ts</code>)입니다. 훅 대신 <code>queryOptions</code>를 만들어 TanStack Query 최신 사용법과 맞고, 생성 코드가 적습니다. 다만 아직 1.0 전 버전입니다.</li>
|
||||
<li><b>orval은 안정적인 성숙형 도구</b>입니다(v8). <code>useGetFeed()</code> 같은 훅을 바로 만들어 주고, 가짜 데이터(MSW) 생성이 강점입니다. 다만 훅 방식이라 최신 추세와는 조금 다릅니다.</li>
|
||||
<li>지금 orval을 고른 이유는 <b>o2o-site-AEO와 같은 방식</b>이기 때문입니다. 처음 말씀드릴 때 "orval도 검증된 표준"이라고만 하고 Hey API가 추세상 앞선다는 점을 분명히 말씀드리지 않았습니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>비교</h2>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>기준</th><th>orval (지금)</th><th>Hey API</th><th>openapi-typescript + openapi-fetch</th><th>Kubb</th></tr>
|
||||
<tr><td>만드는 것</td><td>타입 + API마다 훅 (<code>useGetFeed</code>)</td><td>타입 + SDK + <code>queryOptions</code>/<code>mutationOptions</code></td><td>타입 한 파일 + 아주 작은 fetch 클라이언트</td><td>플러그인 조합 (타입·훅·Zod·MSW 등)</td></tr>
|
||||
<tr><td>TanStack Query</td><td class="g">훅 바로 생성</td><td class="g">플러그인 (최신 권장 방식)</td><td class="w">없음 (openapi-react-query는 유지보수 모드)</td><td class="g">플러그인</td></tr>
|
||||
<tr><td>성숙도</td><td class="g">v8 안정</td><td class="w">1.0 전, 활발히 개발 중</td><td class="g">안정, 가장 가벼움</td><td>안정, 설정 가장 복잡</td></tr>
|
||||
<tr><td>생성 코드 양 (대형 스펙 기준)</td><td>많음 (~14MB)</td><td>적음 (~2.9MB)</td><td>가장 적음 (~2.4MB)</td><td>가장 많음 (~24MB)</td></tr>
|
||||
<tr><td>로그인 토큰·401 처리</td><td>mutator 직접 작성 (지금 <code>custom-fetch.ts</code>)</td><td class="g">인터셉터 내장</td><td>미들웨어</td><td>직접 구성</td></tr>
|
||||
<tr><td>가짜 데이터(MSW)·Zod</td><td class="g">기본 제공</td><td>플러그인</td><td>없음</td><td>플러그인</td></tr>
|
||||
<tr><td>우리에게</td><td class="g">AEO와 같음 → 두 저장소를 오가며 일하기 쉬움</td><td>추세에 맞지만 회사 첫 사용</td><td>캐시 처리를 직접 짜야 함</td><td>우리 규모엔 과함</td></tr>
|
||||
</table></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>바꾸면 드는 일 (Hey API로 갈 경우)</h2>
|
||||
<ul>
|
||||
<li>패키지 교체: <code>orval</code> → <code>@hey-api/openapi-ts</code> (개발용), 설정 파일 1개</li>
|
||||
<li>화면 코드에서 <code>useGetFeed(...)</code>를 <code>useQuery(getFeedOptions(...))</code> 모양으로 바꾸기 (<code>src/b</code> 화면 파일 10여 곳)</li>
|
||||
<li>401 갱신 처리를 Hey API 인터셉터로 옮기기</li>
|
||||
<li>백엔드는 바꿀 것 없음 (OpenAPI 스펙 그대로)</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>출처</h2>
|
||||
<ul>
|
||||
<li><a href="https://www.saschb2b.com/blog/typesafe-api-codegen-2026">Typesafe API Code Generation for React in 2026</a></li>
|
||||
<li><a href="https://dev.to/nyaomaru/which-openapi-codegen-should-you-choose-openapi-typescript-vs-hey-api-vs-orval-vs-kubb-100p">Which OpenAPI Codegen Should You Choose? (DEV)</a></li>
|
||||
<li><a href="https://www.pkgpulse.com/guides/orval-vs-openapi-typescript-vs-kubb-openapi-client-2026">Orval vs openapi-typescript vs Kubb 2026 (PkgPulse)</a></li>
|
||||
<li><a href="https://kubb.dev/docs/5.x/guide/comparison">Kubb 비교 문서</a></li>
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,314 @@
|
||||
<title>날씨각 API 목록</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&family=IBM+Plex+Mono:wght@400&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: 공통 규칙 → 화면별 API 표 → 응답 예시 → 프론트 타입 자동 생성 → 정할 것 */
|
||||
:root{
|
||||
--bg:#f6f7fa; --fg:#1d2330; --muted:#404a5b; --line:#d6dbe5; --soft:#eaeef5; --accent:#2b56a0; --warn:#8f3c17;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#12161e;--fg:#e4e8f0;--muted:#a9b3c4;--line:#2b3342;--soft:#19202b;--accent:#93b5ef;--warn:#f0a07a;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#12161e;--fg:#e4e8f0;--muted:#a9b3c4;--line:#2b3342;--soft:#19202b;--accent:#93b5ef;--warn:#f0a07a;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14.5px;line-height:1.65}
|
||||
main{max-width:1080px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:32px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:22px;margin:0 0 10px;text-wrap:balance}
|
||||
h3{font-size:15px;margin:16px 0 6px}
|
||||
p,li{max-width:76ch}
|
||||
p{margin:0 0 8px}
|
||||
ol,ul{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:5px}
|
||||
.sub{color:var(--muted)}
|
||||
code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:2px 6px;border-radius:3px}
|
||||
pre{font-family:var(--mono);font-size:12.5px;line-height:1.55;background:var(--soft);border:1px solid var(--line);border-radius:6px;padding:14px 16px;overflow-x:auto;margin:0}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:760px}
|
||||
th,td{text-align:left;vertical-align:top;padding:9px 11px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
td.m{font-family:var(--mono);font-size:12.5px;white-space:nowrap}
|
||||
.lock{color:var(--warn);font-weight:600;white-space:nowrap}
|
||||
</style>
|
||||
<main>
|
||||
<header>
|
||||
<h1>날씨각 API 목록</h1>
|
||||
<p class="sub">3단계 · 2026-10-01 · 기준 화면: 시안 B 피드 (탭 5개: 오늘 · 각 · 노을 · 주말·행사 · 계절·상식)</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>공통 규칙 (o2o-site-AEO와 같음)</h2>
|
||||
<ul>
|
||||
<li>주소는 <code>/v1/{도메인}/{동작}</code> 형식입니다. 조회는 GET, 변경은 POST·DELETE를 씁니다.</li>
|
||||
<li>모든 응답에 <code>result: {success, code, desc}</code>가 들어갑니다. 값이 없는 필드(None)는 응답에서 빠집니다.</li>
|
||||
<li>id는 모두 숫자입니다. 지수·읽을거리는 영문 <code>code</code>(예: <code>yajang</code>)를 따로 줘서 아이콘·공유 주소에 씁니다.</li>
|
||||
<li>구는 항상 <code>region</code>(행정코드)으로 지정합니다. 예: 마포구 <code>1144000000</code></li>
|
||||
<li>시각은 ISO 8601 형식(KST <code>+09:00</code>)으로 주고, 날짜는 <code>YYYY-MM-DD</code>로 줍니다.</li>
|
||||
<li>화면 문장은 서버가 만들어서 줍니다. 색·그라데이션·아이콘 그림은 프론트가 정하고, 서버는 <code>icon</code> 이름이나 종류 코드만 줍니다.</li>
|
||||
<li><span class="lock">로그인</span> 표시가 있는 API는 <code>Authorization: Bearer {access}</code> 헤더가 필요합니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>화면별 API</h2>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>화면</th><th>메서드 · 주소</th><th>요청</th><th>응답 요약</th></tr>
|
||||
<tr><td>공통</td><td class="m">GET /healthz</td><td>—</td><td>서버 기동 시각</td></tr>
|
||||
<tr><td>공통</td><td class="m">GET /v1/region/list</td><td><code>q</code>(검색어, 선택)</td><td>구 목록 <code>code, name, short_name</code></td></tr>
|
||||
<tr><td>공통</td><td class="m">GET /v1/region/nearest</td><td><code>lat, lon</code></td><td>가장 가까운 구 1개</td></tr>
|
||||
<tr><td>오늘</td><td class="m">GET /v1/feed</td><td><code>region</code></td><td>하늘 영역, 오늘의 각 줄, 오늘 피드 전부(전국 공통 칸·순서에 그 구 내용을 채움), 피드 사이 띠</td></tr>
|
||||
<tr><td>오늘</td><td class="m">GET /v1/weather/today</td><td><code>region</code></td><td>오늘 3시간 칸 8개(0·3·6…21시): 기온·체감·하늘·비·아이콘·낮/밤/노을·한 줄 메모, 위 한 줄. 피드 "오늘 날씨" 포스트 첫 슬라이드에 씀</td></tr>
|
||||
<tr><td>오늘</td><td class="m">GET /v1/weather/now</td><td><code>region</code></td><td>지금 비 올까: 앞으로 2시간 비(초단기예보), 내일 비 시작 시각·출근 8시·퇴근 7시, 가까운 측정소 미세먼지, 지금 내려진 특보(받지 못했으면 빠짐). 피드 "오늘 날씨" 포스트 2·3번째 슬라이드와 하늘 영역 "지금 비"에 씀</td></tr>
|
||||
<tr><td>오늘</td><td class="m">GET /v1/feed/post/{post_id}</td><td>—</td><td>포스트 1개 (공유 링크로 들어왔을 때)</td></tr>
|
||||
<tr><td>각</td><td class="m">GET /v1/index/list</td><td><code>region</code>, <code>category</code>(선택: 1 밖에서 놀기·2 먹고 마시기·3 집안일·4 생활 고민), <code>core</code>(가을 각만)</td><td>오늘 날씨 점수(<code>weather_score</code>), 1~3위, 지수 전체(점수순, 순위, 한 줄, 오늘·내일·모레 점수)</td></tr>
|
||||
<tr><td>각</td><td class="m">GET /v1/index/{index_id}</td><td><code>region</code></td><td>계산 근거: 6요소 값·비중·문장, 0점 조건, 반영 못 한 것</td></tr>
|
||||
<tr><td>노을</td><td class="m">GET /v1/sky</td><td><code>region</code></td><td>오늘 점수·등급·확신, 3컷 시각, 해 지는 방향, 가까운 명소, 앞으로 3일</td></tr>
|
||||
<tr><td>노을</td><td class="m">GET /v1/sky/ranking</td><td><code>date</code>(선택)</td><td>전국 노을 순위 (대표 30곳)</td></tr>
|
||||
<tr><td>주말·행사</td><td class="m">GET /v1/week</td><td><code>region</code></td><td>7일 날씨 (요일, 공휴일, 아이콘, 최고, 요약, 추천)</td></tr>
|
||||
<tr><td>주말·행사</td><td class="m">GET /v1/week/place/list</td><td><code>region</code>, <code>date</code>, <code>area</code>(선택)</td><td>데이트 명소. 그날 비가 오면 실내를, 맑으면 야외를 먼저</td></tr>
|
||||
<tr><td>주말·행사</td><td class="m">GET /v1/week/event/list</td><td><code>region</code>, <code>area</code>(선택)</td><td>축제·행사, 그날 날씨와 맞는지 한 줄</td></tr>
|
||||
<tr><td>계절·상식</td><td class="m">GET /v1/season/week</td><td>—</td><td>이번 주 특집: 주차, 제목, 시, 지금 절기·다음 절기</td></tr>
|
||||
<tr><td>계절·상식</td><td class="m">GET /v1/season/article/list</td><td><code>category</code>(선택: season·tip·gak)</td><td>읽을거리 목록</td></tr>
|
||||
<tr><td>계절·상식</td><td class="m">GET /v1/season/article/{article_id}</td><td>—</td><td>읽을거리 본문</td></tr>
|
||||
<tr><td>로그인</td><td class="m">POST /v1/auth/signup</td><td><code>login_id</code>(영문 소문자·숫자·_ 4~20), <code>password</code>(8자 이상), <code>nickname</code>(2~12자). 구글 로그인은 이번에 뺌</td><td>access·refresh 토큰</td></tr>
|
||||
<tr><td>로그인</td><td class="m">POST /v1/auth/login</td><td><code>login_id, password</code></td><td>access·refresh 토큰</td></tr>
|
||||
<tr><td>로그인</td><td class="m">POST /v1/auth/refresh</td><td><code>refresh_token</code></td><td>새 access 토큰</td></tr>
|
||||
<tr><td>로그인</td><td class="m">GET /v1/auth/me</td><td><span class="lock">로그인</span></td><td>닉네임, 로그인 방식</td></tr>
|
||||
<tr><td>반응</td><td class="m">POST · DELETE /v1/reaction/post/{post_id}/like</td><td><span class="lock">로그인</span></td><td>좋아요 수, 내가 눌렀는지</td></tr>
|
||||
<tr><td>반응</td><td class="m">POST · DELETE /v1/reaction/post/{post_id}/save</td><td><span class="lock">로그인</span></td><td>저장 여부</td></tr>
|
||||
<tr><td>반응</td><td class="m">GET /v1/reaction/save/list</td><td><span class="lock">로그인</span> <code>cursor</code></td><td>내가 저장한 포스트</td></tr>
|
||||
<tr><td>반응</td><td class="m">GET /v1/reaction/post/{post_id}/comment/list</td><td><code>cursor</code></td><td>댓글 목록 (로그인 없이 보기)</td></tr>
|
||||
<tr><td>반응</td><td class="m">POST /v1/reaction/post/{post_id}/comment</td><td><span class="lock">로그인</span> <code>body</code> (60자)</td><td>만든 댓글</td></tr>
|
||||
<tr><td>반응</td><td class="m">DELETE /v1/reaction/comment/{comment_id}</td><td><span class="lock">로그인</span> 본인 것만</td><td>—</td></tr>
|
||||
<tr><td>반응</td><td class="m">POST · DELETE /v1/reaction/comment/{comment_id}/like</td><td><span class="lock">로그인</span></td><td>좋아요 수</td></tr>
|
||||
<!-- 보류: <tr><td>반응</td><td class="m">POST /v1/reaction/comment/{comment_id}/report</td><td>로그인, reason (1=욕설·비하 2=광고 3=개인정보 노출 4=기타)</td><td>신고 3건이면 자동 숨김</td></tr> -->
|
||||
</table></div>
|
||||
<p class="sub" style="margin-top:8px">보내기(공유)는 API가 없습니다. 보낼 문구는 포스트의 <code>share_messages</code>에 들어 있고, 카카오톡·링크 복사는 프론트에서 처리합니다.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>응답 예시</h2>
|
||||
|
||||
<h3>GET /v1/feed?region=1144000000</h3>
|
||||
<pre>{
|
||||
"result": {"success": true, "code": 0, "desc": "SUCCESS"},
|
||||
"region": {"code": "1144000000", "name": "서울 마포구", "short_name": "마포구"},
|
||||
"hero": {
|
||||
"now_at": "2026-10-01T17:40:00+09:00",
|
||||
"sky_mode": "sunset",
|
||||
"temp_c": 21, "feels_c": 22,
|
||||
"discomfort": {"value": 67, "label": "쾌적"},
|
||||
"rain_2h": {"will_rain": false, "text": "2시간 없음"},
|
||||
"top3": [
|
||||
{"index_id": 1, "code": "yajang", "name": "야장각", "icon": "yajang", "score": 88, "rank": 1},
|
||||
{"index_id": 2, "code": "picnic", "name": "피크닉", "icon": "picnic", "score": 84, "rank": 2},
|
||||
{"index_id": 3, "code": "chimaek", "name": "치맥각", "icon": "chimaek", "score": 83, "rank": 3}
|
||||
],
|
||||
"bubble": {"who": "rabbit", "text": "퇴근하고 야장 가자!"}
|
||||
},
|
||||
"stories": [{"index_id": 1, "code": "yajang", "name": "야장각", "icon": "yajang", "score": 88, "rank": 1}],
|
||||
"posts": [
|
||||
{
|
||||
"post_id": 1024, "position": 2, "post_type": "gak",
|
||||
"title": "야장각 88", "icon": "yajang",
|
||||
"caption": "저녁 7시 21°, 바람은 살랑, 비 없음. 오늘의 각 1위는 야장각이에요.",
|
||||
"slides": [{"kind": "gak", "rank": 1, "score": 88, "name": "야장각", "line": "퇴근하고 야장 가기 딱 좋은 저녁", "summary": "저녁 7시 21°, 바람 살랑"}],
|
||||
"share_messages": ["오늘 야장 어때? 🍻 야장각 88이래"],
|
||||
"like_count": 389, "comment_count": 3, "liked": false, "saved": false,
|
||||
"published_at": "2026-10-01T17:28:00+09:00"
|
||||
},
|
||||
{
|
||||
"post_id": 1023, "position": 1, "post_type": "weather", "title": "오늘 하루의 날씨", "icon": "sun",
|
||||
"slides": [
|
||||
{"kind": "hours", "line": "낮엔 햇볕 따뜻, 저녁엔 선선해요",
|
||||
"hours": [{"at": "2026-10-01T00:00:00+09:00", "icon": "stars", "temp_c": 17, "tone": "night"}]},
|
||||
{"kind": "umbrella", "line": "오늘은 필요 없어요. 내일 오후 3시부터 비",
|
||||
"rows": [{"label": "앞으로 2시간", "value": "비 없음"}, {"label": "내일 출근 8시", "value": "맑음 16°"}]},
|
||||
{"kind": "dust", "line": "초미세먼지 11, 창문 활짝 열어도 돼요",
|
||||
"rows": [{"label": "초미세먼지", "value": "11 좋음"}]}
|
||||
]
|
||||
}
|
||||
],
|
||||
"bands": {
|
||||
"events": [{"event_id": 31, "name": "서울세계불꽃축제", "when": "10월 3일 토요일 밤", "status": "soon", "status_label": "이번 토요일"}],
|
||||
"top5": [{"index_id": 1, "code": "yajang", "name": "야장각", "score": 88, "summary": "저녁 7시 21°, 바람 살랑"}],
|
||||
"season": [{"article_id": 5, "code": "maple", "title": "설악산 첫 단풍, 절정은 언제?", "meta": "계절 소식 · 3분"}]
|
||||
}
|
||||
}</pre>
|
||||
<p class="sub" style="margin-top:8px">슬라이드는 <code>kind</code>마다 모양이 정해져 있습니다: <code>hours</code> · <code>umbrella</code> · <code>dust</code> · <code>gak</code> · <code>sunset</code> · <code>spots</code> · <code>info</code>(계절·행사·상식) · <code>week</code>. 하루 포스트가 10개 안팎이라 나눠 받지 않고 한 번에 다 줍니다. <code>liked</code>·<code>saved</code>는 로그인했을 때만 들어갑니다.</p>
|
||||
|
||||
<h3>GET /v1/index/1?region=1144000000</h3>
|
||||
<pre>{
|
||||
"result": {"success": true, "code": 0, "desc": "SUCCESS"},
|
||||
"index_id": 1, "code": "yajang", "name": "야장각", "score": 88, "rank": 1,
|
||||
"description": "저녁 6시~자정, 바깥 자리에 앉기 좋은 정도",
|
||||
"factors": [
|
||||
{"axis": "temp", "label": "기온", "value": 92, "weight": 30, "note": "체감 21°, 편한 범위 18~24° 안"},
|
||||
{"axis": "rain", "label": "비", "value": 100, "weight": 25, "note": "비 확률 0%"},
|
||||
{"axis": "wind", "label": "바람", "value": 86, "weight": 15, "note": "바람 초속 2m, 전구 줄도 안 흔들려요"},
|
||||
{"axis": "humidity", "label": "습도", "value": 70, "weight": 10, "note": "습도 68%, 살짝 끈적"},
|
||||
{"axis": "air", "label": "공기", "value": 92, "weight": 10, "note": "초미세먼지 11, 좋음"},
|
||||
{"axis": "time", "label": "시간대", "value": 78, "weight": 10, "note": "목요일 저녁이라 주말보다 조금 낮게"}
|
||||
],
|
||||
"zero_rules": "비 확률 80% 이상이거나 바람이 초속 14m를 넘으면 바로 0점",
|
||||
"zero_reason": null,
|
||||
"limit": "모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요",
|
||||
"trend": [{"date": "2026-10-01", "score": 88}, {"date": "2026-10-02", "score": 30}, {"date": "2026-10-03", "score": 70}]
|
||||
}</pre>
|
||||
|
||||
<h3>GET /v1/sky?region=1144000000</h3>
|
||||
<pre>{
|
||||
"result": {
|
||||
"success": true,
|
||||
"code": 0,
|
||||
"desc": "SUCCESS"
|
||||
},
|
||||
"region_code": "1144000000",
|
||||
"sunset_azimuth": 266,
|
||||
"sunset": {
|
||||
"day": "2026-10-02",
|
||||
"sky_type": 1,
|
||||
"score": 48,
|
||||
"grade": 2,
|
||||
"grade_label": "은은함",
|
||||
"confidence": 1,
|
||||
"best_times": [
|
||||
{
|
||||
"at": "2026-10-02T18:15:44.782997+09:00",
|
||||
"kind": "sun",
|
||||
"label": "해 져요"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-02T18:25:44.782997+09:00",
|
||||
"kind": "peak",
|
||||
"label": "가장 붉을 때"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-02T18:41:49.977676+09:00",
|
||||
"kind": "twilight",
|
||||
"label": "보랏빛 하늘"
|
||||
}
|
||||
]
|
||||
},
|
||||
"sunrise": {
|
||||
"day": "2026-10-03",
|
||||
"sky_type": 2,
|
||||
"score": 44,
|
||||
"grade": 2,
|
||||
"grade_label": "은은함",
|
||||
"confidence": 3,
|
||||
"best_times": [
|
||||
{
|
||||
"at": "2026-10-03T06:02:08.797987+09:00",
|
||||
"kind": "twilight",
|
||||
"label": "푸른 새벽"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-03T06:09:14.395594+09:00",
|
||||
"kind": "peak",
|
||||
"label": "가장 붉을 때"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-03T06:28:14.395594+09:00",
|
||||
"kind": "sun",
|
||||
"label": "해 떠요"
|
||||
}
|
||||
]
|
||||
},
|
||||
"days": [
|
||||
{
|
||||
"day": "2026-10-02",
|
||||
"sky_type": 1,
|
||||
"score": 48,
|
||||
"grade": 2,
|
||||
"grade_label": "은은함",
|
||||
"confidence": 1,
|
||||
"best_times": [
|
||||
{
|
||||
"at": "2026-10-02T18:15:44.782997+09:00",
|
||||
"kind": "sun",
|
||||
"label": "해 져요"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-02T18:25:44.782997+09:00",
|
||||
"kind": "peak",
|
||||
"label": "가장 붉을 때"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-02T18:41:49.977676+09:00",
|
||||
"kind": "twilight",
|
||||
"label": "보랏빛 하늘"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"day": "2026-10-03",
|
||||
"sky_type": 1,
|
||||
"score": 48,
|
||||
"grade": 2,
|
||||
"grade_label": "은은함",
|
||||
"confidence": 3,
|
||||
"best_times": [
|
||||
{
|
||||
"at": "2026-10-03T18:14:13.521969+09:00",
|
||||
"kind": "sun",
|
||||
"label": "해 져요"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-03T18:30:13.521969+09:00",
|
||||
"kind": "peak",
|
||||
"label": "가장 붉을 때"
|
||||
},
|
||||
{
|
||||
"at": "2026-10-03T18:40:19.119576+09:00",
|
||||
"kind": "twilight",
|
||||
"label": "보랏빛 하늘"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"spots": [
|
||||
{
|
||||
"no": 1,
|
||||
"name": "망원한강공원",
|
||||
"description": "강 건너 서쪽이 넓게 트임 · 자전거 7분",
|
||||
"lat": 37.5555,
|
||||
"lon": 126.895,
|
||||
"distance_km": 1.5
|
||||
}
|
||||
]
|
||||
}</pre>
|
||||
|
||||
<h3>GET /v1/week?region=1144000000</h3>
|
||||
<pre>{
|
||||
"result": {"success": true, "code": 0, "desc": "SUCCESS"},
|
||||
"days": [
|
||||
{"date": "2026-10-03", "weekday": "토", "holiday": "개천절", "icon": "sun", "temp_max_c": 23, "temp_min_c": 13,
|
||||
"headline": "토요일 · 맑음 13~23°", "summary": "하루 종일 맑음, 피크닉각 86",
|
||||
"pick": "낮엔 여의도 피크닉, 밤엔 불꽃축제", "rain_hours": null},
|
||||
{"date": "2026-10-04", "weekday": "일", "holiday": null, "icon": "rain", "temp_max_c": 20, "temp_min_c": 14,
|
||||
"headline": "일요일 · 오후 2시부터 비 14~20°", "summary": "오전 등산각 78, 오후는 실내",
|
||||
"pick": "아침 북한산 → 오후 성수동 전시", "rain_hours": [14, 20]}
|
||||
]
|
||||
}</pre>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>프론트 연결 (Hey API)</h2>
|
||||
<ol>
|
||||
<li><b>백엔드:</b> 요청·응답을 Pydantic 모델(<code>Req_*</code>/<code>Res_*</code>)로 정의하면 FastAPI가 <code>http://localhost:9810/openapi.json</code>을 자동으로 만듭니다. Swagger는 <code>/docs</code>.</li>
|
||||
<li><b>생성:</b> <code>frontend/</code>에서 <code>npm run api</code> → <code>openapi-ts.config.ts</code>가 스펙을 읽어 <code>src/api/client/</code>에 타입·SDK·TanStack Query 함수를 만듭니다. 서버 없이 뽑을 때는 <code>python backend/scripts/export_openapi.py</code> 후 <code>OPENAPI_INPUT=../backend/openapi.json npm run api</code>.</li>
|
||||
<li><b>이름:</b> operationId 의 <code>_v1_</code> 앞부분을 camelCase 로 줄인다. 예: <code>get_feed_v1_feed_get</code> → <code>getFeedOptions</code>, <code>like_post_v1_…</code> → <code>likePostMutation</code>.</li>
|
||||
<li><b>화면:</b> <code>useQuery(getFeedOptions({ query: { region } }))</code>, <code>useMutation(likePostMutation())</code>. 직접 <code>fetch</code> 하지 않습니다.</li>
|
||||
<li><b>공통 처리:</b> <code>src/api/setup.ts</code> 가 백엔드 주소(<code>VITE_API_BASE_URL</code>), 로그인 토큰, 401 때 토큰 갱신 후 재요청을 맡습니다.</li>
|
||||
<li><b>규칙:</b> 백엔드 API 를 바꾸면 <code>npm run api</code> 를 다시 실행합니다. 생성된 파일은 손으로 고치지 않습니다.</li>
|
||||
</ol>
|
||||
<p class="sub" style="margin-top:8px">도구 비교와 고른 이유: api-codegen.html</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>정할 것</h2>
|
||||
<ul>
|
||||
<li>구를 정하는 방법: 사용자가 고르기만 할지, 위치로 가장 가까운 구를 찾는 것(<code>/v1/region/nearest</code>)도 할지</li>
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,76 @@
|
||||
<title>날씨각 데이터 흐름</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&family=IBM+Plex+Mono:wght@400&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: data-pipeline.md 와 같은 내용 */
|
||||
:root{
|
||||
--bg:#f5f7fb; --fg:#1c2433; --muted:#3f4a5c; --line:#d4dbe7; --soft:#e8edf5; --accent:#2457a6; --warn:#8f3c17; --ok:#1d6b46;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#11161f;--fg:#e3e8f1;--muted:#a9b4c5;--line:#2a3443;--soft:#18202c;--accent:#8fb4f0;--warn:#f0a07a;--ok:#7fd8ab;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#11161f;--fg:#e3e8f1;--muted:#a9b4c5;--line:#2a3443;--soft:#18202c;--accent:#8fb4f0;--warn:#f0a07a;--ok:#7fd8ab;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14.5px;line-height:1.65}
|
||||
main{max-width:1080px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:34px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:22px;margin:0 0 10px;text-wrap:balance}
|
||||
h3{font-size:15px;margin:14px 0 6px}
|
||||
p,li{max-width:76ch}
|
||||
p{margin:0 0 8px}
|
||||
ol,ul{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:5px}
|
||||
.sub{color:var(--muted)}
|
||||
code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:2px 6px;border-radius:3px;overflow-wrap:anywhere}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:780px;font-variant-numeric:tabular-nums}
|
||||
th,td{text-align:left;vertical-align:top;padding:9px 11px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
.tag{display:inline-block;font-size:11.5px;line-height:1.5;padding:1px 7px;border-radius:3px;border:1px solid currentColor;white-space:nowrap}
|
||||
.t-view{color:var(--accent)} .t-time{color:var(--ok)} .t-plan{color:var(--warn)}
|
||||
.ok{color:var(--ok);font-weight:600}
|
||||
</style>
|
||||
<main>
|
||||
<header><h1>날씨각 데이터 흐름</h1>
|
||||
<p class="sub">기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.</p>
|
||||
</header>
|
||||
<section><h2>원칙</h2>
|
||||
<ol><li>외부 API는 <b>첫 사용자가 볼 때</b> 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.</li><li>받자마자 우리 형식으로 바꿔 <b>PostgreSQL</b>에 저장한다. 원본 응답은 저장하지 않는다.</li><li>계산(체감기온, 지수, 노을 점수)은 <b>데이터가 들어올 때 한 번</b> 하고 저장한다.</li><li><b>피드는 전국 공통 1개.</b> 매일 03:00 스케줄러가 그날 포스트의 칸과 순서만 정하고, 칸 안의 숫자·문장은 볼 때 그 구 데이터로 채운다.</li><li><b>Redis</b>는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.</li><li>스케줄은 <b>하루 1번</b>(매일 03:00, worker)만 돈다.</li></ol>
|
||||
</section>
|
||||
<section><h2>한눈에</h2>
|
||||
<div class="wrap"><table><tr><th>데이터</th><th>출처</th><th>언제 받나</th><th>저장 (DB)</th><th>캐시 (Redis)</th></tr><tr><td>시간별·하루 날씨</td><td>기상청 단기예보</td><td>새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때</td><td><code>weather_hourly</code> <code>weather_daily</code></td><td>피드 완성본에 포함</td></tr><tr><td>앞으로 2시간 비</td><td>기상청 초단기예보</td><td>매시 45분 이후 그 구를 처음 볼 때</td><td>저장 안 함</td><td><code>ultra:{구}</code></td></tr><tr><td>4~7일 뒤 날씨</td><td>기상청 중기예보</td><td>새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때</td><td><code>weather_daily</code> (단기예보가 8시간 미만인 날은 중기 값 유지)</td><td>—</td></tr><tr><td>층별 구름</td><td>Open-Meteo (ECMWF·GFS·JMA·ICON)</td><td>오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청</td><td><code>cloud_hourly</code> (일출·일몰 시각 값만)</td><td>—</td></tr><tr><td>미세먼지</td><td>에어코리아 실시간</td><td>매시 20분 이후 처음 볼 때, 전국 1번</td><td><code>air_quality</code></td><td>—</td></tr><tr><td>기상특보</td><td>기상청 기상특보</td><td>매시 정각 이후 처음 볼 때, 전국 1번</td><td><code>weather_warning</code></td><td>—</td></tr><tr><td>축제·행사</td><td>TourAPI (<code>lDongRegnCd</code> = 구 코드 앞 2자리)</td><td>그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌</td><td><code>event</code></td><td>—</td></tr><tr><td>해 시각</td><td>서버 계산 (API 없음)</td><td>그 구의 그날 값이 없을 때</td><td><code>sun_time</code></td><td>—</td></tr><tr><td>측정소 위치</td><td>에어코리아 측정소</td><td>처음 볼 때 + 하루 1번 스케줄</td><td><code>air_station</code></td><td>—</td></tr><tr><td>공휴일 · 24절기</td><td>천문연 특일정보</td><td>그해 값이 없을 때 처음 볼 때 1년치</td><td><code>holiday</code> <code>solar_term</code></td><td>—</td></tr><tr><td>지수·노을 점수</td><td>위 값으로 계산</td><td>재료가 새로 들어온 직후</td><td><code>index_score</code> <code>sky_score</code></td><td>피드 완성본에 포함</td></tr><tr><td>그날 피드 칸·순서</td><td>스케줄러</td><td>매일 03:00</td><td><code>post</code></td><td>—</td></tr><tr><td>피드 완성본</td><td>위 테이블 조립</td><td>캐시가 없을 때</td><td>—</td><td><code>feed:{구}</code></td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>저장하는 곳</h2>
|
||||
<div class="wrap"><table><tr><th>곳</th><th>담는 것</th><th>지워지면</th></tr><tr><td>PostgreSQL</td><td>받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용</td><td>볼륨에 둬서 지워지지 않음. 원본은 여기</td></tr><tr><td>Redis</td><td>피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금</td><td>문제없음. 다음 요청 때 PostgreSQL로 다시 만듦</td></tr><tr><td>시드 파일 (저장소)</td><td>구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리</td><td>git에 있음. 배포할 때 PostgreSQL로 불러옴</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>화면 요청 하나가 처리되는 순서</h2>
|
||||
<p>예: 17:20에 마포구 메인 피드를 연다.</p>
|
||||
<ol><li><b>Redis <code>feed:마포구</code> 확인.</b> 있으면 그대로 돌려준다. 대부분 여기서 끝난다.</li><li><b>없으면 재료가 최신인지 확인.</b><ul><li>단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)</li><li>초단기예보: Redis <code>ultra:마포구</code>가 있나</li><li>미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)</li><li>해 시각: 없으면 계산한다</li></ul></li><li><b>오래된 것만 외부에서 받는다.</b><ul><li>여러 API는 <b>동시에</b> 부른다 (가장 느린 하나만큼만 걸림).</li><li>Redis 잠금 <code>lock:{API}:{구}</code>를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.</li><li>DB에 직전 값이 있으면 <b>그 값으로 먼저 응답</b>하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.</li></ul></li><li><b>받은 값을 우리 형식으로 바꿔 DB에 저장.</b> 체감기온·불쾌지수도 이때 계산.</li><li><b>재료가 바뀌었으면 계산.</b> 지수 24개 × 오늘·내일·모레 → <code>index_score</code>.</li><li><b>피드 완성본 조립.</b> 오늘 <code>post</code> 칸을 순서대로 읽고, 칸마다 그 구 데이터로 제목·캡션·슬라이드·보내기 문구를 만든다. Redis에 넣고 돌려준다.</li></ol>
|
||||
<p>실패할 때:</p>
|
||||
<ul><li>외부 호출이 실패하면 DB의 직전 값으로 응답하고 로그를 남긴다. 완성본은 5분만 캐시해서 5분 뒤 다시 시도.</li><li>잠금을 못 잡으면(다른 요청이 받는 중) 최대 3초 기다렸다가 DB에서 읽는다.</li></ul>
|
||||
</section>
|
||||
<section><h2>최신인지 판단하는 법</h2>
|
||||
<div class="wrap"><table><tr><th>데이터</th><th>"최신" 기준</th></tr><tr><td>단기예보</td><td>02·05·08·11·14·17·20·23시 중 "발표 + 10분"이 지난 마지막 발표. DB의 <code>issued_at</code>이 그보다 이르면 다시 받음</td></tr><tr><td>초단기예보</td><td>매시 30분 발표, 45분부터 제공. Redis에 없으면 다시 받음</td></tr><tr><td>중기예보</td><td>06·18시 발표. DB의 <code>issued_at</code>이 그보다 이르면 다시 받음</td></tr><tr><td>미세먼지</td><td><code>measured_at</code>이 이번 시각(매시 20분 기준)보다 이르면 전국을 다시 받음</td></tr><tr><td>기상특보</td><td>마지막으로 받은 시각이 이번 정시보다 이르면 다시 받음</td></tr><tr><td>층별 구름</td><td>오늘 13시(노을)·21시(일출) 이후에 받은 값이 없으면 다시 받음</td></tr><tr><td>지수 점수</td><td><code>index_score.computed_at</code>이 단기예보 <code>issued_at</code>이나 미세먼지 <code>measured_at</code>보다 이르면 다시 계산</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>Redis 캐시 키</h2>
|
||||
<div class="wrap"><table><tr><th>키</th><th>담는 것</th><th>만료</th><th>미리 지우는 경우</th></tr><tr><td><code>feed:{구 코드}</code></td><td>메인 피드 응답 완성본</td><td>다음 정시 20분(미세먼지)과 다음 단기예보 제공 시각 중 빠른 쪽. 최대 1시간</td><td>03:00 새 피드가 정해졌을 때 (전체)</td></tr><tr><td><code>ultra:{구 코드}</code></td><td>초단기예보 6시간</td><td>다음 정시 45분</td><td>—</td></tr><tr><td><code>rank:sunset:{날짜}</code></td><td>전국 노을 순위 (대표 30곳)</td><td>다음 날 00:00</td><td>—</td></tr><tr><td><code>lock:{API}:{구 코드}</code></td><td>동시 호출 잠금</td><td>10초</td><td>호출이 끝나면 바로 풂</td></tr></table></div>
|
||||
<p>Redis는 compose에서 볼륨 + <code>appendonly yes</code>로 띄운다. 도커를 내렸다 올려도 값이 남는다.</p>
|
||||
</section>
|
||||
<section><h2>출처 주소</h2>
|
||||
<p>모든 data.go.kr API는 최상위 <code>.env</code>의 <code>DATA_GO_KR_SERVICE_KEY</code> 하나를 쓴다 (API마다 활용신청 필요).</p>
|
||||
<div class="wrap"><table><tr><th>출처</th><th>주소</th><th>한 번에 받는 범위</th></tr><tr><td>기상청 단기예보</td><td><code>https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst</code></td><td>구 1곳 (5km 칸 <code>nx</code>,<code>ny</code>). 오늘~모레 1시간 간격, 글피 3시간 간격</td></tr><tr><td>기상청 초단기예보</td><td><code>https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst</code></td><td>구 1곳, 6시간</td></tr><tr><td>기상청 중기예보</td><td><code>https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst</code> · <code>getMidTa</code></td><td>예보 구역 1곳</td></tr><tr><td>기상청 기상특보</td><td><code>https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd</code></td><td>전국</td></tr><tr><td>에어코리아 실시간</td><td><code>https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty</code> (<code>sidoName=전국</code>)</td><td>전국 측정소</td></tr><tr><td>에어코리아 측정소</td><td><code>https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList</code></td><td>전국 측정소</td></tr><tr><td>TourAPI 축제</td><td><code>https://apis.data.go.kr/B551011/KorService2/searchFestival2</code> (지역은 <code>lDongRegnCd</code>, <code>areaCode</code> 아님)</td><td>시도 1곳</td></tr><tr><td>천문연 특일정보</td><td><code>https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo</code></td><td>1개월</td></tr><tr><td>Open-Meteo</td><td><code>https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high</code></td><td>좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음)</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>계산 (데이터가 들어올 때 한 번)</h2>
|
||||
<div class="wrap"><table><tr><th>계산</th><th>계산하는 순간</th><th>재료</th><th>저장</th></tr><tr><td>체감기온, 불쾌지수</td><td>단기예보 저장할 때</td><td>기온·습도·바람</td><td><code>weather_hourly</code></td></tr><tr><td>지수 24개 × 오늘·내일·모레</td><td>단기예보 저장 직후 / 미세먼지 갱신 뒤 첫 조회</td><td>날씨, 미세먼지, 해 시각, 지수 정의</td><td><code>index_score</code></td></tr><tr><td>노을·일출 점수, 3컷 시각</td><td>층별 구름 저장 직후</td><td>구름, 해 시각</td><td><code>sky_score</code></td></tr><tr><td>전국 노을 순위</td><td>13시 이후 순위를 처음 볼 때</td><td><code>sky_score</code></td><td>Redis <code>rank:sunset</code></td></tr><tr><td>포스트 문장</td><td>피드 완성본을 조립할 때</td><td>위 결과 + 문장 틀</td><td>Redis <code>feed:{구}</code></td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>그날 피드 (매일 03:00 스케줄러가 정함, 안 돌았으면 첫 요청에서)</h2>
|
||||
<p>전국 공통 1개. 스케줄러는 <b>칸과 순서, 공개 시각만</b> <code>post</code>에 넣는다. 칸 안의 내용은 볼 때 그 구 데이터로 채운다. 좋아요·댓글은 칸(<code>post_id</code>)에 붙으므로 전국 사용자가 같이 본다. 모든 칸은 다음 날 03:00에 숨는다.</p>
|
||||
<div class="wrap"><table><tr><th>순서</th><th>칸</th><th>공개</th><th><code>ref_type</code> / <code>index_rank</code></th><th>볼 때 채우는 내용</th></tr><tr><td>1</td><td>오늘 날씨</td><td>03:00</td><td>없음</td><td>3시간 칸, 우산(2시간 비·출퇴근), 미세먼지</td></tr><tr><td>2</td><td>지수</td><td>06:00</td><td>없음 / 1위</td><td>그 구 1위 지수</td></tr><tr><td>3</td><td>계절 소식</td><td>09:00</td><td><code>article</code> (날마다 돌아가며)</td><td>글 첫 문단</td></tr><tr><td>4</td><td>행사</td><td>10:00</td><td>없음</td><td>그 시도에서 날짜가 가장 가까운 행사</td></tr><tr><td>5</td><td>지수</td><td>12:00</td><td>없음 / 2위</td><td>그 구 2위 지수</td></tr><tr><td>6</td><td>노을</td><td>13:00</td><td>없음</td><td>점수·3컷, 가까운 명소</td></tr><tr><td>7</td><td>날씨 상식</td><td>15:00</td><td><code>article</code> (날마다 돌아가며)</td><td>글 첫 문단</td></tr><tr><td>8</td><td>주말 추천 (목~일만)</td><td>18:00</td><td>없음</td><td>그 구 토·일 날씨·추천</td></tr></table></div>
|
||||
<p>그 구에 채울 데이터가 없는 칸(예: 그 시도에 행사가 없음)은 그 구 피드에서 건너뛴다. 좋아요·댓글 수와 내가 누른 표시는 캐시와 상관없이 매번 DB에서 덮어쓴다.</p>
|
||||
</section>
|
||||
<section><h2>하루 1번 스케줄 (매일 03:00, worker)</h2>
|
||||
<div class="wrap"><table><tr><th>하는 일</th><th>이유</th></tr><tr><td>그날 피드 칸·순서를 <code>post</code>에 넣고 Redis <code>feed:*</code> 비우기</td><td>전국 공통 피드</td></tr><tr><td>7일 지난 날씨·해 시각, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기</td><td>테이블이 계속 커지지 않게</td></tr><tr><td>에어코리아 측정소 목록 갱신 (전국 1번)</td><td>측정소가 새로 생기거나 없어질 때 반영</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>테스트</h2>
|
||||
<p><code>pytest</code>는 개발 DB를 건드리지 않는다. 실행할 때마다 <code>nalssigak_test</code> DB를 <code>init.sql</code>로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (<code>tests/conftest.py</code>의 <code>offline</code>).</p>
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,138 @@
|
||||
# 날씨각 데이터 흐름
|
||||
|
||||
기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.
|
||||
|
||||
## 원칙
|
||||
|
||||
1. 외부 API는 **첫 사용자가 볼 때** 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.
|
||||
2. 받자마자 우리 형식으로 바꿔 **PostgreSQL**에 저장한다. 원본 응답은 저장하지 않는다.
|
||||
3. 계산(체감기온, 지수, 노을 점수)은 **데이터가 들어올 때 한 번** 하고 저장한다.
|
||||
4. **피드는 전국 공통 1개.** 매일 03:00 스케줄러가 그날 포스트의 칸과 순서만 정하고, 칸 안의 숫자·문장은 볼 때 그 구 데이터로 채운다.
|
||||
5. **Redis**는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.
|
||||
6. 스케줄은 **하루 1번**(매일 03:00, worker)만 돈다.
|
||||
|
||||
## 한눈에
|
||||
|
||||
| 데이터 | 출처 | 언제 받나 | 저장 (DB) | 캐시 (Redis) |
|
||||
|---|---|---|---|---|
|
||||
| 시간별·하루 날씨 | 기상청 단기예보 | 새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때 | `weather_hourly` `weather_daily` | 피드 완성본에 포함 |
|
||||
| 앞으로 2시간 비 | 기상청 초단기예보 | 매시 45분 이후 그 구를 처음 볼 때 | 저장 안 함 | `ultra:{구}` |
|
||||
| 4~7일 뒤 날씨 | 기상청 중기예보 | 새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때 | `weather_daily` (단기예보가 8시간 미만인 날은 중기 값 유지) | — |
|
||||
| 층별 구름 | Open-Meteo (ECMWF·GFS·JMA·ICON) | 오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청 | `cloud_hourly` (일출·일몰 시각 값만) | — |
|
||||
| 미세먼지 | 에어코리아 실시간 | 매시 20분 이후 처음 볼 때, 전국 1번 | `air_quality` | — |
|
||||
| 기상특보 | 기상청 기상특보 | 매시 정각 이후 처음 볼 때, 전국 1번 | `weather_warning` | — |
|
||||
| 축제·행사 | TourAPI (`lDongRegnCd` = 구 코드 앞 2자리) | 그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌 | `event` | — |
|
||||
| 해 시각 | 서버 계산 (API 없음) | 그 구의 그날 값이 없을 때 | `sun_time` | — |
|
||||
| 측정소 위치 | 에어코리아 측정소 | 처음 볼 때 + 하루 1번 스케줄 | `air_station` | — |
|
||||
| 공휴일 · 24절기 | 천문연 특일정보 | 그해 값이 없을 때 처음 볼 때 1년치 | `holiday` `solar_term` | — |
|
||||
| 지수·노을 점수 | 위 값으로 계산 | 재료가 새로 들어온 직후 | `index_score` `sky_score` | 피드 완성본에 포함 |
|
||||
| 그날 피드 칸·순서 | 스케줄러 | 매일 03:00 | `post` | — |
|
||||
| 피드 완성본 | 위 테이블 조립 | 캐시가 없을 때 | — | `feed:{구}` |
|
||||
|
||||
## 저장하는 곳
|
||||
|
||||
| 곳 | 담는 것 | 지워지면 |
|
||||
|---|---|---|
|
||||
| PostgreSQL | 받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용 | 볼륨에 둬서 지워지지 않음. 원본은 여기 |
|
||||
| Redis | 피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금 | 문제없음. 다음 요청 때 PostgreSQL로 다시 만듦 |
|
||||
| 시드 파일 (저장소) | 구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리 | git에 있음. 배포할 때 PostgreSQL로 불러옴 |
|
||||
|
||||
## 화면 요청 하나가 처리되는 순서
|
||||
|
||||
예: 17:20에 마포구 메인 피드를 연다.
|
||||
|
||||
1. **Redis `feed:마포구` 확인.** 있으면 그대로 돌려준다. 대부분 여기서 끝난다.
|
||||
2. **없으면 재료가 최신인지 확인.**
|
||||
- 단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)
|
||||
- 초단기예보: Redis `ultra:마포구`가 있나
|
||||
- 미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)
|
||||
- 해 시각: 없으면 계산한다
|
||||
3. **오래된 것만 외부에서 받는다.**
|
||||
- 여러 API는 **동시에** 부른다 (가장 느린 하나만큼만 걸림).
|
||||
- Redis 잠금 `lock:{API}:{구}`를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.
|
||||
- DB에 직전 값이 있으면 **그 값으로 먼저 응답**하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.
|
||||
4. **받은 값을 우리 형식으로 바꿔 DB에 저장.** 체감기온·불쾌지수도 이때 계산.
|
||||
5. **재료가 바뀌었으면 계산.** 지수 24개 × 오늘·내일·모레 → `index_score`.
|
||||
6. **피드 완성본 조립.** 오늘 `post` 칸을 순서대로 읽고, 칸마다 그 구 데이터로 제목·캡션·슬라이드·보내기 문구를 만든다. Redis에 넣고 돌려준다.
|
||||
|
||||
실패할 때:
|
||||
- 외부 호출이 실패하면 DB의 직전 값으로 응답하고 로그를 남긴다. 완성본은 5분만 캐시해서 5분 뒤 다시 시도.
|
||||
- 잠금을 못 잡으면(다른 요청이 받는 중) 최대 3초 기다렸다가 DB에서 읽는다.
|
||||
|
||||
## 최신인지 판단하는 법
|
||||
|
||||
| 데이터 | "최신" 기준 |
|
||||
|---|---|
|
||||
| 단기예보 | 02·05·08·11·14·17·20·23시 중 "발표 + 10분"이 지난 마지막 발표. DB의 `issued_at`이 그보다 이르면 다시 받음 |
|
||||
| 초단기예보 | 매시 30분 발표, 45분부터 제공. Redis에 없으면 다시 받음 |
|
||||
| 중기예보 | 06·18시 발표. DB의 `issued_at`이 그보다 이르면 다시 받음 |
|
||||
| 미세먼지 | `measured_at`이 이번 시각(매시 20분 기준)보다 이르면 전국을 다시 받음 |
|
||||
| 기상특보 | 마지막으로 받은 시각이 이번 정시보다 이르면 다시 받음 |
|
||||
| 층별 구름 | 오늘 13시(노을)·21시(일출) 이후에 받은 값이 없으면 다시 받음 |
|
||||
| 지수 점수 | `index_score.computed_at`이 단기예보 `issued_at`이나 미세먼지 `measured_at`보다 이르면 다시 계산 |
|
||||
|
||||
## Redis 캐시 키
|
||||
|
||||
| 키 | 담는 것 | 만료 | 미리 지우는 경우 |
|
||||
|---|---|---|---|
|
||||
| `feed:{구 코드}` | 메인 피드 응답 완성본 | 다음 정시 20분(미세먼지)과 다음 단기예보 제공 시각 중 빠른 쪽. 최대 1시간 | 03:00 새 피드가 정해졌을 때 (전체) |
|
||||
| `ultra:{구 코드}` | 초단기예보 6시간 | 다음 정시 45분 | — |
|
||||
| `rank:sunset:{날짜}` | 전국 노을 순위 (대표 30곳) | 다음 날 00:00 | — |
|
||||
| `lock:{API}:{구 코드}` | 동시 호출 잠금 | 10초 | 호출이 끝나면 바로 풂 |
|
||||
|
||||
Redis는 compose에서 볼륨 + `appendonly yes`로 띄운다. 도커를 내렸다 올려도 값이 남는다.
|
||||
|
||||
## 출처 주소
|
||||
|
||||
모든 data.go.kr API는 최상위 `.env`의 `DATA_GO_KR_SERVICE_KEY` 하나를 쓴다 (API마다 활용신청 필요).
|
||||
|
||||
| 출처 | 주소 | 한 번에 받는 범위 |
|
||||
|---|---|---|
|
||||
| 기상청 단기예보 | `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst` | 구 1곳 (5km 칸 `nx`,`ny`). 오늘~모레 1시간 간격, 글피 3시간 간격 |
|
||||
| 기상청 초단기예보 | `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst` | 구 1곳, 6시간 |
|
||||
| 기상청 중기예보 | `https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst` · `getMidTa` | 예보 구역 1곳 |
|
||||
| 기상청 기상특보 | `https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd` | 전국 |
|
||||
| 에어코리아 실시간 | `https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty` (`sidoName=전국`) | 전국 측정소 |
|
||||
| 에어코리아 측정소 | `https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList` | 전국 측정소 |
|
||||
| TourAPI 축제 | `https://apis.data.go.kr/B551011/KorService2/searchFestival2` (지역은 `lDongRegnCd`, `areaCode` 아님) | 시도 1곳 |
|
||||
| 천문연 특일정보 | `https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo` | 1개월 |
|
||||
| Open-Meteo | `https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high` | 좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음) |
|
||||
|
||||
## 계산 (데이터가 들어올 때 한 번)
|
||||
|
||||
| 계산 | 계산하는 순간 | 재료 | 저장 |
|
||||
|---|---|---|---|
|
||||
| 체감기온, 불쾌지수 | 단기예보 저장할 때 | 기온·습도·바람 | `weather_hourly` |
|
||||
| 지수 24개 × 오늘·내일·모레 | 단기예보 저장 직후 / 미세먼지 갱신 뒤 첫 조회 | 날씨, 미세먼지, 해 시각, 지수 정의 | `index_score` |
|
||||
| 노을·일출 점수, 3컷 시각 | 층별 구름 저장 직후 | 구름, 해 시각 | `sky_score` |
|
||||
| 전국 노을 순위 | 13시 이후 순위를 처음 볼 때 | `sky_score` | Redis `rank:sunset` |
|
||||
| 포스트 문장 | 피드 완성본을 조립할 때 | 위 결과 + 문장 틀 | Redis `feed:{구}` |
|
||||
|
||||
## 그날 피드 (매일 03:00 스케줄러가 정함, 안 돌았으면 첫 요청에서)
|
||||
|
||||
전국 공통 1개. 스케줄러는 **칸과 순서, 공개 시각만** `post`에 넣는다. 칸 안의 내용은 볼 때 그 구 데이터로 채운다. 좋아요·댓글은 칸(`post_id`)에 붙으므로 전국 사용자가 같이 본다. 모든 칸은 다음 날 03:00에 숨는다.
|
||||
|
||||
| 순서 | 칸 | 공개 | `ref_type` / `index_rank` | 볼 때 채우는 내용 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | 오늘 날씨 | 03:00 | 없음 | 3시간 칸, 우산(2시간 비·출퇴근), 미세먼지 |
|
||||
| 2 | 지수 | 06:00 | 없음 / 1위 | 그 구 1위 지수 |
|
||||
| 3 | 계절 소식 | 09:00 | `article` (날마다 돌아가며) | 글 첫 문단 |
|
||||
| 4 | 행사 | 10:00 | 없음 | 그 시도에서 날짜가 가장 가까운 행사 |
|
||||
| 5 | 지수 | 12:00 | 없음 / 2위 | 그 구 2위 지수 |
|
||||
| 6 | 노을 | 13:00 | 없음 | 점수·3컷, 가까운 명소 |
|
||||
| 7 | 날씨 상식 | 15:00 | `article` (날마다 돌아가며) | 글 첫 문단 |
|
||||
| 8 | 주말 추천 (목~일만) | 18:00 | 없음 | 그 구 토·일 날씨·추천 |
|
||||
|
||||
그 구에 채울 데이터가 없는 칸(예: 그 시도에 행사가 없음)은 그 구 피드에서 건너뛴다. 좋아요·댓글 수와 내가 누른 표시는 캐시와 상관없이 매번 DB에서 덮어쓴다.
|
||||
|
||||
## 하루 1번 스케줄 (매일 03:00, worker)
|
||||
|
||||
| 하는 일 | 이유 |
|
||||
|---|---|
|
||||
| 그날 피드 칸·순서를 `post`에 넣고 Redis `feed:*` 비우기 | 전국 공통 피드 |
|
||||
| 7일 지난 날씨·해 시각, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기 | 테이블이 계속 커지지 않게 |
|
||||
| 에어코리아 측정소 목록 갱신 (전국 1번) | 측정소가 새로 생기거나 없어질 때 반영 |
|
||||
|
||||
## 테스트
|
||||
|
||||
`pytest`는 개발 DB를 건드리지 않는다. 실행할 때마다 `nalssigak_test` DB를 `init.sql`로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (`tests/conftest.py`의 `offline`).
|
||||
@@ -0,0 +1,113 @@
|
||||
<title>날씨각 지수 기준 초안</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: 계산 방식 → 요소별 점수 규칙 → 지수 23개 표 → 오늘 날씨 점수 → 확인할 것 */
|
||||
:root{
|
||||
--bg:#fbf8f3; --fg:#24201b; --muted:#4e463c; --line:#e2d9cc; --soft:#f2ebe0; --accent:#b4531f; --fun:#6b4bb0;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#17140f;--fg:#efe8dd;--muted:#bdb2a3;--line:#352e25;--soft:#211c16;--accent:#f0a06c;--fun:#b9a2f0;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#17140f;--fg:#efe8dd;--muted:#bdb2a3;--line:#352e25;--soft:#211c16;--accent:#f0a06c;--fun:#b9a2f0;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14px;line-height:1.6}
|
||||
main{max-width:1200px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:30px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:21px;margin:0 0 10px;text-wrap:balance}
|
||||
p,li{max-width:80ch}
|
||||
p{margin:0 0 8px}
|
||||
ul,ol{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:4px}
|
||||
.sub{color:var(--muted)}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:1100px;font-variant-numeric:tabular-nums}
|
||||
th,td{text-align:left;vertical-align:top;padding:8px 10px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
td.n{white-space:nowrap;font-weight:600}
|
||||
.fun{color:var(--fun);font-size:12px;font-weight:600}
|
||||
.core{color:var(--accent);font-size:12px;font-weight:600}
|
||||
.w{white-space:nowrap}
|
||||
</style>
|
||||
<main>
|
||||
<header>
|
||||
<h1>활동 지수 기준 초안</h1>
|
||||
<p class="sub"><b>구현 반영됨 (2026-10-02).</b> 이름은 모두 "~각"으로 통일했고(예: 반려견 산책 → 멍뭉산책각), 실제 값은 <code>backend/seed/index_definition.json</code> 이 기준입니다. · 4번 기능용 · 2026-10-02 · 시안의 비중·0점 조건·근거 문장을 그대로 가져오고, 목업에 없던 요소별 점수 규칙과 나머지 10개 지수 비중은 제가 새로 채웠습니다.</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2>계산 방식 (모든 지수 공통)</h2>
|
||||
<ol>
|
||||
<li>지수마다 정한 <b>시간대</b>(예: 야장각 18~24시)의 시간별 날씨를 봅니다.</li>
|
||||
<li>6요소(기온·비·바람·습도·공기·시간대)를 각각 0~100점으로 바꿉니다. 아래 "요소별 점수 규칙"을 씁니다.</li>
|
||||
<li>지수별 <b>비중</b>으로 더해 0~100점을 냅니다.</li>
|
||||
<li><b>바로 0점 조건</b>에 걸리면 0점입니다.</li>
|
||||
<li>오늘·내일·모레를 같은 방식으로 계산합니다. 각 화면의 막대 3개가 이것입니다.</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>요소별 점수 규칙</h2>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>요소</th><th>쓰는 값</th><th>규칙 종류</th></tr>
|
||||
<tr><td>기온</td><td>시간대 평균 체감기온</td><td><b>범위</b>: 편한 범위 안이면 100, 1°C 벗어날 때마다 8점 감점 · <b>높을수록</b>: A°C 0점 → B°C 100점 · <b>낮을수록</b>: 반대</td></tr>
|
||||
<tr><td>비</td><td>시간대 최대 비 확률</td><td><b>마를수록</b>: 100 − 확률 (비가 실제로 오면 0) · <b>올수록</b>: 확률 그대로 (비 오는 날 좋은 지수)</td></tr>
|
||||
<tr><td>바람</td><td>시간대 최대 풍속</td><td><b>잔잔할수록</b>: 기준 이하 100, 한계에서 0 · <b>적당히</b>: 2~5m/s 100 (빨래용)</td></tr>
|
||||
<tr><td>습도</td><td>시간대 평균 습도</td><td><b>범위</b>: 40~60% 100, 1%당 2점 감점 · <b>높을수록</b> / <b>낮을수록</b></td></tr>
|
||||
<tr><td>공기</td><td>가까운 측정소 초미세먼지</td><td>15 이하 100 → 75 이상 0 (사이는 직선)</td></tr>
|
||||
<tr><td>시간대</td><td>요일·시각·달</td><td>지수마다 다름 (아래 표). 달 밝기는 서버가 날짜로 계산 (외부 API 없음)</td></tr>
|
||||
</table></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>지수 23개</h2>
|
||||
<p class="sub">비중 순서: 기온 · 비 · 바람 · 습도 · 공기 · 시간대 (합 100). <span class="core">가을</span> = 이번 계절 핵심(<code>is_core</code>), <span class="fun">재미</span> = 재미로 보는 지수(<code>is_fun</code>).</p>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>지수</th><th>시간대</th><th>비중</th><th>기온</th><th>비</th><th>바람</th><th>습도</th><th>시간대 점수</th><th>바로 0점</th><th>반영 못 한 것</th></tr>
|
||||
<tr><td class="n">야장각 <span class="fun">재미</span></td><td class="w">18~24시</td><td class="w">30·25·15·10·10·10</td><td>범위 18~24°</td><td>마를수록</td><td>잔잔 ≤2, 한계 10</td><td>범위</td><td>금·토 100, 일 85, 평일 78</td><td>비 확률 80% 이상, 바람 14m/s 이상</td><td>모기, 영업 여부, 자리 경쟁</td></tr>
|
||||
<tr><td class="n">피크닉 <span class="core">가을</span></td><td class="w">11~16시</td><td class="w">30·25·15·10·10·10</td><td>범위 20~26°</td><td>마를수록</td><td>잔잔 ≤3, 한계 9</td><td>범위</td><td>주말·공휴일 100, 평일 60</td><td>비 확률 60% 이상</td><td>잔디 상태, 공원 혼잡도</td></tr>
|
||||
<tr><td class="n">치맥각 <span class="fun">재미</span></td><td class="w">18~23시</td><td class="w">30·20·15·15·10·10</td><td>범위 20~27°</td><td>마를수록</td><td>잔잔 ≤3, 한계 10</td><td>범위</td><td>금·토 100, 평일 74</td><td>체감 10° 미만, 비 확률 80% 이상</td><td>야구 경기 같은 이벤트</td></tr>
|
||||
<tr><td class="n">산책</td><td class="w">18~22시</td><td class="w">30·25·15·10·15·5</td><td>범위 15~23°</td><td>마를수록</td><td>잔잔 ≤3, 한계 10</td><td>범위</td><td>해 진 뒤 55, 노을 무렵 100</td><td>비 확률 90% 이상, 초미세먼지 75 이상</td><td>길 공사, 조명</td></tr>
|
||||
<tr><td class="n">환기</td><td class="w">10~18시 중 가장 좋은 2시간</td><td class="w">10·15·15·10·45·5</td><td>범위 15~26°</td><td>마를수록</td><td>적당히</td><td>범위</td><td>낮 100</td><td>초미세먼지 75 이상</td><td>집 방향, 주변 공사 먼지</td></tr>
|
||||
<tr><td class="n">등산 <span class="core">가을</span></td><td class="w">7~12시</td><td class="w">30·25·20·10·10·5</td><td>범위 10~20° (정상 기준 −6°)</td><td>마를수록</td><td>잔잔 ≤4, 한계 12</td><td>범위</td><td>주말 100, 평일 50</td><td>비 확률 70% 이상, 강풍주의보</td><td>등산로 통제, 낙석</td></tr>
|
||||
<tr><td class="n">세차</td><td class="w">오늘 + 앞으로 이틀</td><td class="w">5·60·10·10·10·5</td><td>범위 5~28°</td><td>마를수록 (이틀 최대)</td><td>잔잔 ≤4, 한계 10</td><td>낮을수록</td><td>낮 100, 밤 40</td><td>이틀 안 비 70% 이상 → 20점 아래</td><td>황사·꽃가루</td></tr>
|
||||
<tr><td class="n">캠핑 <span class="core">가을</span></td><td class="w">18~다음날 8시</td><td class="w">30·25·15·15·10·5</td><td>범위 12~22°</td><td>마를수록</td><td>잔잔 ≤3, 한계 9</td><td>낮을수록 (이슬)</td><td>금·토 100, 평일 60</td><td>비 확률 60% 이상, 강풍</td><td>캠핑장 예약</td></tr>
|
||||
<tr><td class="n">러닝</td><td class="w">6~8시, 19~22시 중 좋은 쪽</td><td class="w">35·20·10·20·10·5</td><td>범위 8~18°</td><td>마를수록</td><td>잔잔 ≤4, 한계 10</td><td>낮을수록</td><td>아침·저녁 100, 늦은 밤 40</td><td>체감 35° 이상, 비 확률 90% 이상</td><td>노면 상태</td></tr>
|
||||
<tr><td class="n">별보기 <span class="core">가을</span></td><td class="w">21~02시</td><td class="w">5·15·5·10·20·45</td><td>범위 5~25°</td><td>마를수록</td><td>잔잔 ≤5, 한계 12</td><td>낮을수록</td><td>달이 어두울수록 100 (보름 20)</td><td>하늘 흐림(전체 구름) 80% 이상</td><td>도시 불빛 (지역 평균만)</td></tr>
|
||||
<tr><td class="n">짬뽕각 <span class="fun">재미</span></td><td class="w">11~14시, 17~20시</td><td class="w">40·25·15·10·5·5</td><td>낮을수록 (25° 0점 → 5° 100점)</td><td>올수록</td><td>셀수록</td><td>높을수록</td><td>식사 시간 100</td><td>없음</td><td>실제 주문량 검증 전</td></tr>
|
||||
<tr><td class="n">막걸리각 <span class="fun">재미</span></td><td class="w">17~22시</td><td class="w">15·50·10·15·5·5</td><td>낮을수록 (28° 0점 → 10° 100점)</td><td>올수록</td><td>셀수록</td><td>높을수록</td><td>금·토 100, 평일 50</td><td>없음</td><td>실제 판매량 검증 전</td></tr>
|
||||
<tr><td class="n">아아→뜨아 <span class="fun">재미</span></td><td class="w">7~10시</td><td class="w">50·10·15·10·5·10</td><td>낮을수록 (22° 0점 → 8° 100점)</td><td>올수록</td><td>셀수록</td><td>높을수록</td><td>아침 100, 낮 30</td><td>없음</td><td>사람마다 달라요</td></tr>
|
||||
<tr><td class="n">빨래 잘 마름</td><td class="w">9~16시</td><td class="w">20·35·20·20·0·5</td><td>높을수록 (10° → 25°)</td><td>마를수록</td><td>적당히</td><td>낮을수록</td><td>낮 100</td><td>비 확률 60% 이상</td><td>집 일조량</td></tr>
|
||||
<tr><td class="n">자전거</td><td class="w">9~19시</td><td class="w">25·25·30·5·10·5</td><td>범위 15~24°</td><td>마를수록</td><td>잔잔 ≤3, 한계 8</td><td>범위</td><td>주말 100, 평일 70</td><td>비 확률 70% 이상, 바람 10m/s 이상</td><td>자전거 도로 공사</td></tr>
|
||||
<tr><td class="n">반려견 산책</td><td class="w">7~9시, 17~20시</td><td class="w">40·25·10·5·15·5</td><td>범위 5~22° (노면이 뜨거운 30° 이상은 크게 감점)</td><td>마를수록</td><td>잔잔 ≤5, 한계 12</td><td>범위</td><td>아침·저녁 100</td><td>체감 33° 이상, 초미세먼지 75 이상</td><td>노면 온도 실측</td></tr>
|
||||
<tr><td class="n">안경김서림</td><td class="w">7~9시</td><td class="w">50·10·5·30·0·5</td><td>낮을수록 (15° 0점 → −5° 100점)</td><td>올수록</td><td>무관</td><td>높을수록</td><td>출근 시간 100</td><td>없음</td><td>실내 온도</td></tr>
|
||||
<tr><td class="n">화장붕괴</td><td class="w">10~18시</td><td class="w">40·10·10·35·0·5</td><td>높을수록 (20° 0점 → 32° 100점)</td><td>올수록</td><td>셀수록</td><td>높을수록</td><td>낮 100</td><td>없음</td><td>피부 타입</td></tr>
|
||||
<tr><td class="n">냉면각 <span class="fun">재미</span></td><td class="w">11~14시</td><td class="w">55·15·5·15·5·5</td><td>높을수록 (18° 0점 → 32° 100점)</td><td>마를수록</td><td>잔잔</td><td>높을수록</td><td>점심 100</td><td>없음</td><td>검증 전</td></tr>
|
||||
<tr><td class="n">택시대란</td><td class="w">22~02시</td><td class="w">15·55·10·5·0·15</td><td>낮을수록 (15° 0점 → −5° 100점)</td><td>올수록</td><td>셀수록</td><td>무관</td><td>금·토 밤 100, 평일 40</td><td>없음</td><td>행사·공연 종료 시간</td></tr>
|
||||
<tr><td class="n">배달폭주</td><td class="w">17~21시</td><td class="w">20·50·10·5·5·10</td><td>낮을수록 또는 30° 이상 (양 끝)</td><td>올수록</td><td>셀수록</td><td>무관</td><td>금·토·일 100, 평일 60</td><td>없음</td><td>실제 배달 앱 지표 검증 전</td></tr>
|
||||
<tr><td class="n">가드닝</td><td class="w">7~10시</td><td class="w">30·30·10·15·10·5</td><td>범위 12~25°</td><td>마를수록 (물 주기 기준)</td><td>잔잔 ≤4, 한계 10</td><td>범위</td><td>아침 100</td><td>비 확률 70% 이상 (물 줄 필요 없음)</td><td>식물 종류</td></tr>
|
||||
<tr><td class="n">사진산책</td><td class="w">일몰 ±1시간</td><td class="w">15·25·10·5·15·30</td><td>범위 10~26°</td><td>마를수록</td><td>잔잔 ≤5, 한계 12</td><td>노을 점수를 그대로 (0~100)</td><td>비 확률 80% 이상</td><td>장소 혼잡도</td></tr>
|
||||
</table></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>오늘 날씨 점수 (메인 하늘 영역의 숫자)</h2>
|
||||
<p>"오늘 밖에 나가기 좋은 정도"입니다. 지수와 같은 방식으로, 낮 9~21시를 봅니다.</p>
|
||||
<div class="wrap"><table>
|
||||
<tr><th>요소</th><th>비중</th><th>규칙</th></tr>
|
||||
<tr><td>기온</td><td>40</td><td>체감 범위 18~24°</td></tr>
|
||||
<tr><td>비</td><td>30</td><td>마를수록</td></tr>
|
||||
<tr><td>바람</td><td>15</td><td>잔잔 ≤4, 한계 12</td></tr>
|
||||
<tr><td>공기</td><td>15</td><td>초미세먼지 규칙</td></tr>
|
||||
</table></div>
|
||||
<p class="sub" style="margin-top:8px">바로 0점 조건은 없습니다. 비가 와도 0점이 아니라 낮게 나옵니다.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>확인할 것</h2>
|
||||
<ul>
|
||||
<li>시안의 13개 지수는 비중·0점 조건·반영 못 한 것을 시안 그대로 썼습니다. 나머지 10개(빨래부터 사진산책까지)는 제가 새로 정한 값입니다.</li>
|
||||
<li>재미 지수는 "실제 주문량·판매량 검증 전"이라 숫자를 날씨로만 짐작합니다.</li>
|
||||
<li>등산의 "정상 기온"은 산 목록이 없어서 구 기온에서 6°C를 빼서 씁니다.</li>
|
||||
<li>한 줄 요약·1위 긴 문장·토끼/곰 말풍선 문장은 지수 계산을 만든 뒤 문장 초안을 따로 보여드리겠습니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,319 @@
|
||||
-- 날씨각 전체 DDL. DB 를 처음 만들 때만 실행된다 (FK 없음, 코드값 SMALLINT, 시각 UTC).
|
||||
|
||||
DO $$ BEGIN EXECUTE format('ALTER DATABASE %I SET timezone TO ''UTC''', current_database()); END $$;
|
||||
SET timezone TO 'UTC';
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
-- 받아 온 날씨
|
||||
|
||||
-- 구별 시간별 날씨. 출처: 기상청 단기예보. 새 예보가 오면 같은 (구, 시각) 줄을 덮어쓴다.
|
||||
CREATE TABLE IF NOT EXISTS public.weather_hourly (
|
||||
region_code VARCHAR(10) NOT NULL, -- region.code
|
||||
forecast_at TIMESTAMPTZ NOT NULL, -- 몇 시 날씨인지 (정시)
|
||||
temp_c NUMERIC(4,1) NOT NULL, -- 기온 ℃
|
||||
feels_c NUMERIC(4,1) NOT NULL, -- 체감기온 ℃ (저장할 때 계산)
|
||||
discomfort_index SMALLINT NOT NULL, -- 불쾌지수 (저장할 때 계산)
|
||||
sky SMALLINT NOT NULL, -- Sky: 1=맑음 2=구름많음 3=흐림
|
||||
rain_type SMALLINT NOT NULL, -- RainType: 1=없음 2=비 3=비/눈 4=눈 5=소나기
|
||||
rain_prob SMALLINT NOT NULL, -- 비 올 확률 %
|
||||
rain_mm NUMERIC(5,1) NOT NULL DEFAULT 0, -- 1시간 비 양 mm (눈은 녹은 양)
|
||||
humidity SMALLINT NOT NULL, -- 습도 %
|
||||
wind_ms NUMERIC(4,1) NULL, -- 바람 m/s. 글피(3시간 간격 구간)는 기상청이 숫자를 안 줘서 NULL
|
||||
issued_at TIMESTAMPTZ NOT NULL, -- 기상청이 낸 예보 시각
|
||||
PRIMARY KEY (region_code, forecast_at)
|
||||
);
|
||||
|
||||
-- 구별 하루 날씨. 최저·최고는 단기예보, 단기예보 범위 밖 날짜는 중기예보로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.weather_daily (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
forecast_date DATE NOT NULL,
|
||||
temp_min_c NUMERIC(4,1) NULL,
|
||||
temp_max_c NUMERIC(4,1) NULL,
|
||||
sky SMALLINT NOT NULL, -- 그날 대표 하늘 (Sky)
|
||||
rain_type SMALLINT NOT NULL, -- 그날 대표 강수 (RainType)
|
||||
rain_prob SMALLINT NOT NULL, -- 그날 최대 비 확률 %
|
||||
issued_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (region_code, forecast_date)
|
||||
);
|
||||
|
||||
-- 지점별 층별 구름. 노을·일출 점수용 (구마다 해 지는 쪽·뜨는 쪽 20·50·100km 지점).
|
||||
CREATE TABLE IF NOT EXISTS public.cloud_hourly (
|
||||
lat NUMERIC(5,2) NOT NULL, -- 소수 둘째 자리 반올림 값
|
||||
lon NUMERIC(5,2) NOT NULL,
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
model SMALLINT NOT NULL, -- CloudModel: 1=ECMWF 2=GFS 3=JMA 4=ICON (모델끼리 비교해 노을 확신을 낸다)
|
||||
cloud_low SMALLINT NOT NULL, -- 낮은 구름 % (약 2km 아래)
|
||||
cloud_mid SMALLINT NOT NULL, -- 중간 구름 %
|
||||
cloud_high SMALLINT NOT NULL, -- 높은 구름 % (약 6km 위)
|
||||
PRIMARY KEY (lat, lon, forecast_at, model)
|
||||
);
|
||||
|
||||
-- 미세먼지 측정소. 출처: 에어코리아 측정소 정보 (하루 1번 갱신).
|
||||
CREATE TABLE IF NOT EXISTS public.air_station (
|
||||
station_name VARCHAR(30) PRIMARY KEY, -- 전국에서 겹치지 않음 (2026-10 실측 672곳)
|
||||
lat NUMERIC(8,5) NOT NULL,
|
||||
lon NUMERIC(8,5) NOT NULL
|
||||
);
|
||||
|
||||
-- 측정소별 지금 미세먼지. 출처: 에어코리아 실시간 (최신 값만).
|
||||
CREATE TABLE IF NOT EXISTS public.air_quality (
|
||||
station_name VARCHAR(30) PRIMARY KEY, -- air_station.station_name
|
||||
pm25 SMALLINT NULL, -- 초미세먼지 ㎍/㎥ (측정소 점검 중이면 NULL)
|
||||
pm10 SMALLINT NULL, -- 미세먼지 ㎍/㎥
|
||||
grade SMALLINT NULL, -- AirGrade: 1=좋음 2=보통 3=나쁨 4=매우나쁨 (둘 중 나쁜 쪽)
|
||||
measured_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
-- 지금 내려진 기상특보. 받을 때마다 전체를 바꿔 넣는다.
|
||||
CREATE TABLE IF NOT EXISTS public.weather_warning (
|
||||
warning_zone_code VARCHAR(10) NOT NULL, -- 기상청 특보 구역 코드
|
||||
warning_type SMALLINT NOT NULL, -- WarningType: 기상청 warnVar 그대로 (1=강풍 2=호우 3=한파 4=건조 5=폭풍해일 6=풍랑 7=태풍 8=대설 9=황사 12=폭염 13=열대야)
|
||||
level SMALLINT NOT NULL, -- WarningLevel: 1=주의보 2=경보 3=중대경보
|
||||
PRIMARY KEY (warning_zone_code, warning_type)
|
||||
);
|
||||
|
||||
-- 계산 결과 (데이터가 들어올 때 한 번 계산)
|
||||
|
||||
-- 구별 해 시각. 그날 값이 없을 때 서버가 계산해 넣는다 (외부 API 없음).
|
||||
CREATE TABLE IF NOT EXISTS public.sun_time (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
sun_date DATE NOT NULL,
|
||||
sunrise_at TIMESTAMPTZ NOT NULL,
|
||||
sunset_at TIMESTAMPTZ NOT NULL,
|
||||
dusk_end_at TIMESTAMPTZ NOT NULL, -- 시민박명 끝 (보랏빛 하늘 컷, 노을 포스트 end_at)
|
||||
sunset_azimuth SMALLINT NOT NULL, -- 해 지는 방향 도 (예: 262)
|
||||
PRIMARY KEY (region_code, sun_date)
|
||||
);
|
||||
|
||||
-- 구별 노을·일출 점수.
|
||||
CREATE TABLE IF NOT EXISTS public.sky_score (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
score_date DATE NOT NULL,
|
||||
sky_type SMALLINT NOT NULL, -- SkyType: 1=노을 2=일출
|
||||
score SMALLINT NOT NULL, -- 0~100
|
||||
grade SMALLINT NOT NULL, -- SkyGrade: 점수 구간 (화면 문구는 앱에서)
|
||||
confidence SMALLINT NOT NULL, -- Confidence: 1=높음 2=보통 3=낮음
|
||||
best_times JSONB NOT NULL, -- 가장 예쁜 3컷 [{"at": "...", "label": "가장 붉을 때"}]
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, sky_type)
|
||||
);
|
||||
|
||||
-- 구별 지수 점수. 오늘·내일·모레를 날짜별 줄로 둔다 (각 화면의 막대 3개).
|
||||
CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
score_date DATE NOT NULL,
|
||||
index_id SMALLINT NOT NULL, -- index_definition.index_id
|
||||
score SMALLINT NOT NULL, -- 0~100 (0점 조건에 걸리면 0)
|
||||
summary VARCHAR(100) NOT NULL, -- 한 줄 요약 ("저녁 7시 21°, 바람 살랑")
|
||||
temp_score SMALLINT NOT NULL, -- 요소별 0~100
|
||||
rain_score SMALLINT NOT NULL,
|
||||
wind_score SMALLINT NOT NULL,
|
||||
humidity_score SMALLINT NOT NULL,
|
||||
air_score SMALLINT NOT NULL,
|
||||
time_score SMALLINT NOT NULL,
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
|
||||
-- 피드 포스트. 매일 03:00 스케줄러가 그날 전국 공통 피드의 칸과 순서를 정하고, 내용은 볼 때 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
post_id BIGSERIAL PRIMARY KEY,
|
||||
feed_date DATE NOT NULL,
|
||||
position SMALLINT NOT NULL, -- 피드 순서 (1부터)
|
||||
post_type SMALLINT NOT NULL, -- PostType: 1=오늘날씨 2=지수 3=노을 4=계절소식 5=행사 6=상식 7=주말추천
|
||||
ref_type SMALLINT NOT NULL DEFAULT 1, -- RefType: 1=없음(그 구 데이터로 채움) 2=index_definition 3=article 4=event
|
||||
ref_id BIGINT NULL, -- ref_type 이 가리키는 테이블의 id
|
||||
index_rank SMALLINT NULL, -- 지수 포스트가 "그 구의 N위 지수"일 때 N
|
||||
like_count INTEGER NOT NULL DEFAULT 0,
|
||||
comment_count INTEGER NOT NULL DEFAULT 0,
|
||||
published_at TIMESTAMPTZ NOT NULL,
|
||||
end_at TIMESTAMPTZ NULL, -- NULL = 그날 끝까지
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed ON public.post (feed_date, position) WHERE deleted = FALSE;
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
-- 사용자. 일반(아이디·비밀번호) 또는 구글 로그인. 이름·전화번호는 받지 않는다.
|
||||
CREATE TABLE IF NOT EXISTS public.users (
|
||||
user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글
|
||||
login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_<sub>
|
||||
password VARCHAR(255) NULL, -- bcrypt 해시. 구글 계정은 NULL
|
||||
provider_uid VARCHAR(255) NULL, -- 구글 sub. 일반 계정은 NULL
|
||||
nickname VARCHAR(30) NOT NULL, -- 댓글에 보이는 이름
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
||||
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_login_id ON public.users (login_id) WHERE deleted = FALSE;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_google ON public.users (provider_uid) WHERE provider = 2 AND deleted = FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.post_like (
|
||||
post_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (post_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.post_save (
|
||||
post_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (post_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_post_save_user ON public.post_save (user_id, created_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment (
|
||||
comment_id BIGSERIAL PRIMARY KEY,
|
||||
post_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
body VARCHAR(60) NOT NULL, -- 시안 입력칸 최대 60자
|
||||
like_count INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_post ON public.comment (post_id, created_at) WHERE deleted = FALSE;
|
||||
|
||||
-- 댓글 신고 (보류)
|
||||
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
|
||||
-- ALTER TABLE public.comment ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
-- CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
-- comment_id BIGINT NOT NULL,
|
||||
-- user_id UUID NOT NULL,
|
||||
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
-- PRIMARY KEY (comment_id, user_id)
|
||||
-- );
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
comment_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
CREATE TABLE IF NOT EXISTS public.region (
|
||||
code VARCHAR(10) PRIMARY KEY, -- 행정표준코드
|
||||
name VARCHAR(30) NOT NULL, -- "서울 마포구"
|
||||
short_name VARCHAR(20) NOT NULL, -- "마포구"
|
||||
lat NUMERIC(8,5) NOT NULL, -- 구 중심
|
||||
lon NUMERIC(8,5) NOT NULL,
|
||||
nx SMALLINT NOT NULL, -- 기상청 5km 칸 번호
|
||||
ny SMALLINT NOT NULL,
|
||||
warning_zone_code VARCHAR(10) NOT NULL, -- 기상청 특보 구역
|
||||
mid_land_code VARCHAR(10) NOT NULL, -- 기상청 중기 육상예보 구역 (예: 11B00000)
|
||||
mid_temp_code VARCHAR(10) NOT NULL, -- 기상청 중기 기온예보 지점 (예: 11B10101 서울)
|
||||
is_ranking_spot BOOLEAN NOT NULL DEFAULT FALSE, -- 전국 노을 순위 대표 지점인지
|
||||
ranking_note VARCHAR(30) NULL -- 순위 옆 설명 ("서해 수평선")
|
||||
);
|
||||
|
||||
-- 지수 정의.
|
||||
CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
index_id SMALLSERIAL PRIMARY KEY,
|
||||
code VARCHAR(30) NOT NULL UNIQUE, -- 영문 이름 (아이콘·주소용, 예: yajang)
|
||||
name VARCHAR(20) NOT NULL, -- "야장각"
|
||||
icon VARCHAR(30) NOT NULL,
|
||||
category SMALLINT NOT NULL, -- IndexCategory: 1=밖에서 놀기 2=먹고 마시기 3=집안일 4=생활 고민
|
||||
is_fun BOOLEAN NOT NULL DEFAULT FALSE, -- 재미로 보는 지수
|
||||
is_core BOOLEAN NOT NULL DEFAULT FALSE, -- 이번 계절 핵심 ("가을 각")
|
||||
has_detail BOOLEAN NOT NULL DEFAULT TRUE, -- 계산 근거 화면이 있는지
|
||||
description VARCHAR(100) NOT NULL, -- 무엇을 재는지
|
||||
windows JSONB NOT NULL, -- 계산 시간대 [{"from": 18, "to": 24}] 여러 개면 가장 좋은 쪽, {"around": "sunset"} 은 일몰 ±1시간
|
||||
weight_temp SMALLINT NOT NULL, -- 6요소 비중 (합 100)
|
||||
weight_rain SMALLINT NOT NULL,
|
||||
weight_wind SMALLINT NOT NULL,
|
||||
weight_humidity SMALLINT NOT NULL,
|
||||
weight_air SMALLINT NOT NULL,
|
||||
weight_time SMALLINT NOT NULL,
|
||||
factor_rules JSONB NOT NULL, -- 요소별 점수 규칙 {"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {...}, ...}
|
||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
spot_id SERIAL PRIMARY KEY,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
name VARCHAR(40) NOT NULL, -- "망원한강공원"
|
||||
description VARCHAR(100) NOT NULL, -- "강 건너 서쪽이 넓게 트임 · 자전거 7분"
|
||||
lat NUMERIC(8,5) NOT NULL,
|
||||
lon NUMERIC(8,5) NOT NULL,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭).
|
||||
CREATE TABLE IF NOT EXISTS public.place (
|
||||
place_id SERIAL PRIMARY KEY,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원")
|
||||
name VARCHAR(40) NOT NULL,
|
||||
is_outdoor BOOLEAN NOT NULL, -- 맑으면 야외, 비 오면 실내를 먼저
|
||||
icon VARCHAR(30) NOT NULL,
|
||||
reason VARCHAR(60) NOT NULL, -- "돗자리 펴고 낮 피크닉"
|
||||
best_time VARCHAR(30) NOT NULL, -- "낮 12시~4시"
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
-- 축제·행사.
|
||||
CREATE TABLE IF NOT EXISTS public.event (
|
||||
event_id BIGSERIAL PRIMARY KEY,
|
||||
source_id VARCHAR(20) NULL UNIQUE, -- TourAPI contentid (직접 넣은 행사는 NULL)
|
||||
sido_code VARCHAR(2) NOT NULL, -- 시도 코드 (TourAPI lDongRegnCd, 서울=11)
|
||||
region_code VARCHAR(10) NULL, -- 구를 알 때만
|
||||
area VARCHAR(20) NULL, -- place.area 와 같은 묶음, NULL = 전체
|
||||
name VARCHAR(60) NOT NULL,
|
||||
place_name VARCHAR(60) NOT NULL, -- "여의도 한강공원"
|
||||
icon VARCHAR(30) NOT NULL DEFAULT 'calendar', -- TourAPI 는 아이콘이 없어 기본값
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
is_confirmed BOOLEAN NOT NULL DEFAULT FALSE, -- FALSE = 예년 기준 일정 (화면에 "확인 필요" 표시)
|
||||
source_url VARCHAR(500) NULL
|
||||
);
|
||||
|
||||
-- 공휴일 (주말·행사 탭의 "개천절").
|
||||
CREATE TABLE IF NOT EXISTS public.holiday (
|
||||
holiday_date DATE NOT NULL,
|
||||
name VARCHAR(20) NOT NULL,
|
||||
PRIMARY KEY (holiday_date, name) -- 같은 날 공휴일이 둘일 수 있다 (예: 2025-05-05)
|
||||
);
|
||||
|
||||
-- 24절기.
|
||||
CREATE TABLE IF NOT EXISTS public.solar_term (
|
||||
term_date DATE PRIMARY KEY,
|
||||
name VARCHAR(10) NOT NULL
|
||||
);
|
||||
|
||||
-- 계절 책 주차 (이번 주 특집의 시).
|
||||
CREATE TABLE IF NOT EXISTS public.season_week (
|
||||
year SMALLINT NOT NULL,
|
||||
week SMALLINT NOT NULL, -- ISO 주차
|
||||
headline VARCHAR(60) NOT NULL, -- "추분 지나 8일째, 가을이 깊어져요"
|
||||
poem_lines JSONB NOT NULL, -- 시 구절 목록 (저작권 만료 작품만)
|
||||
author VARCHAR(60) NOT NULL, -- "윤동주, 「별 헤는 밤」"
|
||||
PRIMARY KEY (year, week)
|
||||
);
|
||||
|
||||
-- 읽을거리 (계절·상식 탭). 계절 소식·날씨 상식·각 원리.
|
||||
CREATE TABLE IF NOT EXISTS public.article (
|
||||
article_id SERIAL PRIMARY KEY,
|
||||
code VARCHAR(40) NOT NULL UNIQUE, -- 영문 이름 (주소용, 예: maple)
|
||||
category SMALLINT NOT NULL, -- ArticleCategory: 1=계절 소식 2=날씨 상식 3=각 원리
|
||||
title VARCHAR(80) NOT NULL,
|
||||
read_minutes SMALLINT NOT NULL, -- "3분"
|
||||
icon VARCHAR(30) NOT NULL,
|
||||
body JSONB NOT NULL, -- 문단 목록
|
||||
show_from DATE NULL, -- 계절 소식이 보이는 기간 (NULL = 늘)
|
||||
show_until DATE NULL,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
pythonpath = .
|
||||
@@ -0,0 +1,14 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
pydantic>=2.0
|
||||
pydantic-settings
|
||||
orjson
|
||||
sqlalchemy>=2.0
|
||||
asyncpg
|
||||
greenlet
|
||||
redis>=5.0
|
||||
httpx
|
||||
apscheduler>=3.10,<4
|
||||
pytest
|
||||
python-jose[cryptography]
|
||||
bcrypt
|
||||
Whitespace-only changes.
@@ -0,0 +1,52 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.auth.account import router as auth_router
|
||||
from router.v1.feed.feed import router as feed_router
|
||||
from router.v1.index.index import router as index_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.weather.weather import router as weather_router
|
||||
from router.v1.week.week import router as week_router
|
||||
|
||||
API_SERVER_START_TIME = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
DB_SESSION_MNG.start()
|
||||
yield
|
||||
await DB_SESSION_MNG.stop()
|
||||
await REDIS.stop()
|
||||
|
||||
|
||||
app = FastAPI(title="날씨각 API", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
app.include_router(region_router)
|
||||
app.include_router(weather_router)
|
||||
app.include_router(sky_router)
|
||||
app.include_router(index_router)
|
||||
app.include_router(week_router)
|
||||
app.include_router(season_router)
|
||||
app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
started_at: datetime
|
||||
db: bool
|
||||
redis: bool
|
||||
|
||||
|
||||
@app.get("/healthz", response_model=Res_Health, response_model_exclude_none=True, summary="헬스체크")
|
||||
async def healthz() -> Res_Health:
|
||||
return Res_Health(started_at=API_SERVER_START_TIME, db=await DB_SESSION_MNG.ping(), redis=await REDIS.ping())
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,44 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Res_Auth, Res_Me
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _me(u: User) -> Me:
|
||||
return Me(login_id=u.login_id, nickname=u.nickname, provider=AuthProvider(u.provider))
|
||||
|
||||
|
||||
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Auth(result=error_info(err))
|
||||
access, refresh = service.tokens(user)
|
||||
return Res_Auth(access_token=access, refresh_token=refresh, me=_me(user))
|
||||
|
||||
|
||||
@router.post("/signup", response_model=Res_Auth, response_model_exclude_none=True, summary="회원가입 (아이디 영문 소문자·숫자·_ 4~20자, 비밀번호 8자 이상, 닉네임 2~12자)")
|
||||
async def signup(req: Req_Signup, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.signup(req.login_id, req.password, req.nickname.strip())
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/login", response_model=Res_Auth, response_model_exclude_none=True, summary="로그인")
|
||||
async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.login(req.login_id, req.password)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급")
|
||||
async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.refresh(req.refresh_token)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.get("/me", response_model=Res_Me, response_model_exclude_none=True, summary="내 정보")
|
||||
async def me(user: User = Depends(current_user)) -> Res_Me:
|
||||
return Res_Me(me=_me(user))
|
||||
@@ -0,0 +1,35 @@
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import AuthProvider
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Req_Signup(Req_WebPacketProtocol):
|
||||
login_id: str
|
||||
password: str
|
||||
nickname: str
|
||||
|
||||
|
||||
class Req_Login(Req_WebPacketProtocol):
|
||||
login_id: str
|
||||
password: str
|
||||
|
||||
|
||||
class Req_Refresh(Req_WebPacketProtocol):
|
||||
refresh_token: str
|
||||
|
||||
|
||||
class Me(WebPacketProtocol):
|
||||
login_id: str
|
||||
nickname: str
|
||||
provider: AuthProvider
|
||||
|
||||
|
||||
class Res_Auth(Res_WebPacketProtocol):
|
||||
access_token: Optional[str] = None
|
||||
refresh_token: Optional[str] = None
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
Whitespace-only changes.
@@ -0,0 +1,42 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.auth import optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.feed.protocol import Res_Feed, Res_Post
|
||||
from services.feed_service import FeedService
|
||||
from services.reaction_service import ReactionService
|
||||
|
||||
router = APIRouter(prefix="/v1/feed", tags=["feed"])
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
|
||||
async def get_feed(
|
||||
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user),
|
||||
service: FeedService = Depends(), reactions: ReactionService = Depends(),
|
||||
) -> Res_Feed:
|
||||
err, feed = await service.feed(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Feed(result=error_info(err))
|
||||
ids = [p.post_id for p in feed.posts]
|
||||
counts = await reactions.counts(ids)
|
||||
liked, saved = await reactions.marks(user, ids)
|
||||
for p in feed.posts:
|
||||
p.like_count, p.comment_count = counts.get(p.post_id, (p.like_count, p.comment_count))
|
||||
if user is not None:
|
||||
p.liked, p.saved = p.post_id in liked, p.post_id in saved
|
||||
return feed
|
||||
|
||||
|
||||
@router.get("/post/{post_id}", response_model=Res_Post, response_model_exclude_none=True, summary="포스트 하나 (공유 링크로 들어왔을 때)")
|
||||
async def get_post(post_id: int = Path(...), region: str = Query(...), service: FeedService = Depends()) -> Res_Post:
|
||||
err, feed = await service.feed(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Post(result=error_info(err))
|
||||
post = next((p for p in feed.posts if p.post_id == post_id), None)
|
||||
if post is None:
|
||||
return Res_Post(result=error_info(ErrorType.NOT_FOUND))
|
||||
return Res_Post(post=post)
|
||||
@@ -0,0 +1,151 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Annotated, Literal, Optional, Union
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import PostType, SlotTone
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Row(WebPacketProtocol):
|
||||
label: str
|
||||
value: str
|
||||
|
||||
|
||||
class HourCell(WebPacketProtocol):
|
||||
label: str
|
||||
icon: str
|
||||
temp_c: Optional[float] = None
|
||||
tone: SlotTone
|
||||
|
||||
|
||||
class HoursSlide(WebPacketProtocol):
|
||||
kind: Literal["hours"]
|
||||
eyebrow: str
|
||||
line: str
|
||||
hours: list[HourCell]
|
||||
|
||||
|
||||
class RowsSlide(WebPacketProtocol):
|
||||
"""우산·미세먼지·계절 소식·행사·상식처럼 '한 줄 + 표' 모양."""
|
||||
|
||||
kind: Literal["rows"]
|
||||
eyebrow: str
|
||||
line: str
|
||||
icon: str
|
||||
rows: list[Row] = []
|
||||
|
||||
|
||||
class GakSlide(WebPacketProtocol):
|
||||
kind: Literal["gak"]
|
||||
index_id: int
|
||||
code: str
|
||||
name: str
|
||||
rank: int
|
||||
score: int
|
||||
line: str
|
||||
summary: str
|
||||
|
||||
|
||||
class Cut(WebPacketProtocol):
|
||||
at: datetime
|
||||
kind: str
|
||||
label: str
|
||||
|
||||
|
||||
class SunsetSlide(WebPacketProtocol):
|
||||
kind: Literal["sunset"]
|
||||
eyebrow: str
|
||||
line: str
|
||||
score: int
|
||||
grade_label: str
|
||||
cuts: list[Cut]
|
||||
|
||||
|
||||
class WeekDay(WebPacketProtocol):
|
||||
day: date
|
||||
weekday: str
|
||||
icon: str
|
||||
text: str
|
||||
|
||||
|
||||
class WeekSlide(WebPacketProtocol):
|
||||
kind: Literal["week"]
|
||||
eyebrow: str
|
||||
line: str
|
||||
days: list[WeekDay]
|
||||
|
||||
|
||||
Slide = Annotated[Union[HoursSlide, RowsSlide, GakSlide, SunsetSlide, WeekSlide], Field(discriminator="kind")]
|
||||
|
||||
|
||||
class PostData(WebPacketProtocol):
|
||||
post_id: int
|
||||
post_type: PostType
|
||||
title: str
|
||||
icon: str
|
||||
caption: str
|
||||
slides: list[Slide]
|
||||
share_messages: list[str] = []
|
||||
like_count: int
|
||||
comment_count: int
|
||||
published_at: datetime
|
||||
liked: Optional[bool] = None
|
||||
saved: Optional[bool] = None
|
||||
|
||||
|
||||
class TopIndex(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
name: str
|
||||
icon: str
|
||||
score: int
|
||||
rank: int
|
||||
summary: Optional[str] = None
|
||||
|
||||
|
||||
class Hero(WebPacketProtocol):
|
||||
now_at: datetime
|
||||
sky_mode: Literal["morning", "day", "sunset", "night"]
|
||||
temp_c: Optional[float] = None
|
||||
feels_c: Optional[float] = None
|
||||
discomfort: Optional[int] = None
|
||||
discomfort_label: Optional[str] = None
|
||||
rain_2h_text: Optional[str] = None
|
||||
will_rain_2h: Optional[bool] = None
|
||||
weather_score: Optional[int] = None
|
||||
top3: list[TopIndex] = []
|
||||
bubble: Optional[str] = None
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
event_id: int
|
||||
name: str
|
||||
status_label: str
|
||||
icon: str
|
||||
|
||||
|
||||
class BandArticle(WebPacketProtocol):
|
||||
article_id: int
|
||||
title: str
|
||||
meta: str
|
||||
icon: str
|
||||
|
||||
|
||||
class Bands(WebPacketProtocol):
|
||||
events: list[BandEvent] = []
|
||||
top5: list[TopIndex] = []
|
||||
season: list[BandArticle] = []
|
||||
|
||||
|
||||
class Res_Feed(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
region_name: Optional[str] = None
|
||||
hero: Optional[Hero] = None
|
||||
stories: list[TopIndex] = []
|
||||
posts: list[PostData] = []
|
||||
bands: Optional[Bands] = None
|
||||
|
||||
|
||||
class Res_Post(Res_WebPacketProtocol):
|
||||
post: Optional[PostData] = None
|
||||
Whitespace-only changes.
@@ -0,0 +1,56 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from common.models.errors import error_info
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, TrendPoint
|
||||
from services.calc.index_calc import AXES, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService
|
||||
|
||||
router = APIRouter(prefix="/v1/index", tags=["index"])
|
||||
|
||||
_AXIS_LABEL = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "공기", "time": "시간대"}
|
||||
|
||||
|
||||
def _summary(i: IndexItem) -> IndexSummary:
|
||||
d = i.definition
|
||||
return IndexSummary(
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, score=t.score) for t in i.trend],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)")
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
core: bool = Query(False, description="이번 계절 핵심 지수만"),
|
||||
service: IndexService = Depends(),
|
||||
) -> Res_IndexList:
|
||||
err, board = await service.board(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i) for i in board.items]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
|
||||
|
||||
|
||||
@router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거")
|
||||
async def get_index(index_id: int = Path(...), region: str = Query(..., description="구 행정코드"), service: IndexService = Depends()) -> Res_IndexDetail:
|
||||
err, board = await service.board(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexDetail(result=error_info(err))
|
||||
item = next((i for i in board.items if i.definition.index_id == index_id), None)
|
||||
if item is None:
|
||||
return Res_IndexDetail(result=error_info(ErrorType.NOT_FOUND))
|
||||
d, s = item.definition, item.score
|
||||
return Res_IndexDetail(
|
||||
index=_summary(item), description=d.description,
|
||||
factors=[
|
||||
Factor(axis=a, label=_AXIS_LABEL[a], value=getattr(s, f"{a}_score"), weight=getattr(d, f"weight_{a}"), note=s.notes.get(a, ""))
|
||||
for a in AXES
|
||||
],
|
||||
zero_rules=zero_rules_text(d.zero_rules), zero_reason=s.zero_reason, limit=d.limit_description,
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import IndexCategory
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class TrendPoint(WebPacketProtocol):
|
||||
day: date
|
||||
score: int
|
||||
|
||||
|
||||
class IndexSummary(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
name: str
|
||||
icon: str
|
||||
category: IndexCategory
|
||||
is_fun: bool
|
||||
is_core: bool
|
||||
score: int
|
||||
rank: int
|
||||
summary: str
|
||||
trend: list[TrendPoint] = []
|
||||
|
||||
|
||||
class Res_IndexList(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
day: Optional[date] = None
|
||||
weather_score: Optional[int] = None
|
||||
top3: list[IndexSummary] = []
|
||||
items: list[IndexSummary] = []
|
||||
|
||||
|
||||
class Factor(WebPacketProtocol):
|
||||
axis: str
|
||||
label: str
|
||||
value: int
|
||||
weight: int
|
||||
note: str
|
||||
|
||||
|
||||
class Res_IndexDetail(Res_WebPacketProtocol):
|
||||
index: Optional[IndexSummary] = None
|
||||
description: Optional[str] = None
|
||||
factors: list[Factor] = []
|
||||
zero_rules: Optional[str] = None
|
||||
zero_reason: Optional[str] = None
|
||||
limit: Optional[str] = None
|
||||
Whitespace-only changes.
@@ -0,0 +1,54 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import PostType
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Res_PostLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
|
||||
|
||||
class Res_PostSave(Res_WebPacketProtocol):
|
||||
saved: Optional[bool] = None
|
||||
|
||||
|
||||
class SavedPost(WebPacketProtocol):
|
||||
post_id: int
|
||||
post_type: PostType
|
||||
feed_date: date
|
||||
saved_at: datetime
|
||||
|
||||
|
||||
class Res_SavedList(Res_WebPacketProtocol):
|
||||
posts: list[SavedPost] = []
|
||||
next_cursor: Optional[int] = None
|
||||
|
||||
|
||||
class CommentData(WebPacketProtocol):
|
||||
comment_id: int
|
||||
nickname: str
|
||||
body: str
|
||||
like_count: int
|
||||
liked: bool
|
||||
mine: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Res_CommentList(Res_WebPacketProtocol):
|
||||
comments: list[CommentData] = []
|
||||
next_cursor: Optional[int] = None
|
||||
|
||||
|
||||
class Req_Comment(Req_WebPacketProtocol):
|
||||
body: str
|
||||
|
||||
|
||||
class Res_Comment(Res_WebPacketProtocol):
|
||||
comment: Optional[CommentData] = None
|
||||
|
||||
|
||||
class Res_CommentLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
@@ -0,0 +1,93 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType, PostType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
from router.v1.reaction.protocol import (
|
||||
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
|
||||
)
|
||||
from services.reaction_service import PAGE, CommentView, ReactionService
|
||||
|
||||
router = APIRouter(prefix="/v1/reaction", tags=["reaction"])
|
||||
|
||||
|
||||
def _comment(v: CommentView) -> CommentData:
|
||||
c = v.comment
|
||||
return CommentData(comment_id=c.comment_id, nickname=v.nickname, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, created_at=c.created_at.astimezone(KST))
|
||||
|
||||
|
||||
async def _like(post_id: int, user: User, on: bool, service: ReactionService) -> Res_PostLike:
|
||||
err, count = await service.like_post(post_id, user, on)
|
||||
return Res_PostLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요")
|
||||
async def like_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, user, True, service)
|
||||
|
||||
|
||||
@router.delete("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 취소")
|
||||
async def unlike_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, user, False, service)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/save", response_model=Res_PostSave, response_model_exclude_none=True, summary="저장")
|
||||
async def save_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostSave:
|
||||
err = await service.save_post(post_id, user, True)
|
||||
return Res_PostSave(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostSave(saved=True)
|
||||
|
||||
|
||||
@router.delete("/post/{post_id}/save", response_model=Res_PostSave, response_model_exclude_none=True, summary="저장 취소")
|
||||
async def unsave_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostSave:
|
||||
err = await service.save_post(post_id, user, False)
|
||||
return Res_PostSave(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostSave(saved=False)
|
||||
|
||||
|
||||
@router.get("/save/list", response_model=Res_SavedList, response_model_exclude_none=True, summary="내가 저장한 포스트")
|
||||
async def list_saved(cursor: Optional[int] = Query(None), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_SavedList:
|
||||
err, items = await service.saved(user, cursor)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_SavedList(result=error_info(err))
|
||||
posts = [SavedPost(post_id=i.post.post_id, post_type=PostType(i.post.post_type), feed_date=i.post.feed_date, saved_at=i.saved_at.astimezone(KST)) for i in items]
|
||||
return Res_SavedList(posts=posts, next_cursor=posts[-1].post_id if len(posts) == PAGE else None)
|
||||
|
||||
|
||||
@router.get("/post/{post_id}/comment/list", response_model=Res_CommentList, response_model_exclude_none=True, summary="댓글 목록 (로그인 없이 보기)")
|
||||
async def list_comments(
|
||||
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), service: ReactionService = Depends()
|
||||
) -> Res_CommentList:
|
||||
err, items = await service.comments(post_id, user, cursor)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_CommentList(result=error_info(err))
|
||||
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자)")
|
||||
async def add_comment(post_id: int = Path(...), req: Req_Comment = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_Comment:
|
||||
err, v = await service.add_comment(post_id, user, req.body)
|
||||
return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v))
|
||||
|
||||
|
||||
@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기")
|
||||
async def delete_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, user)))
|
||||
|
||||
|
||||
async def _clike(comment_id: int, user: User, on: bool, service: ReactionService) -> Res_CommentLike:
|
||||
err, count = await service.like_comment(comment_id, user, on)
|
||||
return Res_CommentLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_CommentLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요")
|
||||
async def like_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, True, service)
|
||||
|
||||
|
||||
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
||||
async def unlike_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, False, service)
|
||||
Whitespace-only changes.
@@ -0,0 +1,19 @@
|
||||
from typing import Optional
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class RegionData(WebPacketProtocol):
|
||||
code: str
|
||||
name: str
|
||||
short_name: str
|
||||
lat: float
|
||||
lon: float
|
||||
|
||||
|
||||
class Res_RegionList(Res_WebPacketProtocol):
|
||||
regions: list[RegionData] = []
|
||||
|
||||
|
||||
class Res_Region(Res_WebPacketProtocol):
|
||||
region: Optional[RegionData] = None
|
||||
@@ -0,0 +1,32 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.region.protocol import RegionData, Res_Region, Res_RegionList
|
||||
from services.region_service import RegionService
|
||||
|
||||
router = APIRouter(prefix="/v1/region", tags=["region"])
|
||||
|
||||
|
||||
def _to_data(r) -> RegionData:
|
||||
return RegionData(code=r.code, name=r.name, short_name=r.short_name, lat=float(r.lat), lon=float(r.lon))
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_RegionList, response_model_exclude_none=True, summary="구 목록")
|
||||
async def list_regions(q: Optional[str] = Query(None, description="구 이름 검색어"), service: RegionService = Depends()) -> Res_RegionList:
|
||||
err, regions = await service.search(q)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_RegionList(result=error_info(err))
|
||||
return Res_RegionList(regions=[_to_data(r) for r in regions])
|
||||
|
||||
|
||||
@router.get("/nearest", response_model=Res_Region, response_model_exclude_none=True, summary="위치에서 가장 가까운 구")
|
||||
async def nearest_region(
|
||||
lat: float = Query(..., ge=33.0, le=39.0), lon: float = Query(..., ge=124.0, le=132.0), service: RegionService = Depends()
|
||||
) -> Res_Region:
|
||||
err, region = await service.nearest(lat, lon)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Region(result=error_info(err))
|
||||
return Res_Region(region=_to_data(region))
|
||||
Whitespace-only changes.
@@ -0,0 +1,42 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import ArticleCategory
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class TermData(WebPacketProtocol):
|
||||
name: str
|
||||
day: date
|
||||
|
||||
|
||||
class ArticleSummary(WebPacketProtocol):
|
||||
article_id: int
|
||||
code: str
|
||||
category: ArticleCategory
|
||||
title: str
|
||||
read_minutes: int
|
||||
icon: str
|
||||
|
||||
|
||||
class Res_SeasonWeek(Res_WebPacketProtocol):
|
||||
year: Optional[int] = None
|
||||
week: Optional[int] = None
|
||||
start: Optional[date] = None
|
||||
end: Optional[date] = None
|
||||
headline: Optional[str] = None
|
||||
poem_lines: list[str] = []
|
||||
author: Optional[str] = None
|
||||
term_now: Optional[TermData] = None
|
||||
term_next: Optional[TermData] = None
|
||||
progress: Optional[float] = None
|
||||
news: list[ArticleSummary] = []
|
||||
|
||||
|
||||
class Res_ArticleList(Res_WebPacketProtocol):
|
||||
articles: list[ArticleSummary] = []
|
||||
|
||||
|
||||
class Res_Article(Res_WebPacketProtocol):
|
||||
article: Optional[ArticleSummary] = None
|
||||
body: list[str] = []
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.database.model.models import Article
|
||||
from common.enums import ArticleCategory, ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.season.protocol import ArticleSummary, Res_Article, Res_ArticleList, Res_SeasonWeek, TermData
|
||||
from services.season_service import SeasonService
|
||||
|
||||
router = APIRouter(prefix="/v1/season", tags=["season"])
|
||||
|
||||
|
||||
def _summary(a: Article) -> ArticleSummary:
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon)
|
||||
|
||||
|
||||
@router.get("/week", response_model=Res_SeasonWeek, response_model_exclude_none=True, summary="이번 주 계절 책: 시, 절기, 계절 소식")
|
||||
async def get_season_week(service: SeasonService = Depends()) -> Res_SeasonWeek:
|
||||
err, v = await service.this_week()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_SeasonWeek(result=error_info(err))
|
||||
return Res_SeasonWeek(
|
||||
year=v.year, week=v.week, start=v.start, end=v.end, headline=v.headline,
|
||||
poem_lines=v.poem.poem_lines if v.poem else [], author=v.poem.author if v.poem else None,
|
||||
term_now=TermData(name=v.term_now.name, day=v.term_now.term_date) if v.term_now else None,
|
||||
term_next=TermData(name=v.term_next.name, day=v.term_next.term_date) if v.term_next else None,
|
||||
progress=v.progress, news=[_summary(a) for a in v.news],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/article/list", response_model=Res_ArticleList, response_model_exclude_none=True, summary="읽을거리 목록")
|
||||
async def list_articles(category: Optional[ArticleCategory] = Query(None), service: SeasonService = Depends()) -> Res_ArticleList:
|
||||
err, items = await service.articles(category)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_ArticleList(result=error_info(err))
|
||||
return Res_ArticleList(articles=[_summary(a) for a in items])
|
||||
|
||||
|
||||
@router.get("/article/{article_id}", response_model=Res_Article, response_model_exclude_none=True, summary="읽을거리 본문")
|
||||
async def get_article(article_id: int = Path(...), service: SeasonService = Depends()) -> Res_Article:
|
||||
err, a = await service.article(article_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Article(result=error_info(err))
|
||||
return Res_Article(article=_summary(a), body=a.body)
|
||||
Whitespace-only changes.
@@ -0,0 +1,53 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class BestTime(WebPacketProtocol):
|
||||
at: datetime
|
||||
kind: str
|
||||
label: str
|
||||
|
||||
|
||||
class SkyScoreData(WebPacketProtocol):
|
||||
day: date
|
||||
sky_type: SkyType
|
||||
score: int
|
||||
grade: SkyGrade
|
||||
grade_label: str
|
||||
confidence: Confidence
|
||||
best_times: list[BestTime] = []
|
||||
|
||||
|
||||
class SpotData(WebPacketProtocol):
|
||||
no: int
|
||||
name: str
|
||||
description: str
|
||||
lat: float
|
||||
lon: float
|
||||
distance_km: float
|
||||
|
||||
|
||||
class Res_Sky(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
sunset_azimuth: Optional[int] = None
|
||||
sunset: Optional[SkyScoreData] = None
|
||||
sunrise: Optional[SkyScoreData] = None
|
||||
days: list[SkyScoreData] = []
|
||||
spots: list[SpotData] = []
|
||||
|
||||
|
||||
class RankData(WebPacketProtocol):
|
||||
rank: int
|
||||
region_code: str
|
||||
name: str
|
||||
note: Optional[str] = None
|
||||
score: int
|
||||
grade: SkyGrade
|
||||
|
||||
|
||||
class Res_SkyRanking(Res_WebPacketProtocol):
|
||||
day: Optional[date] = None
|
||||
items: list[RankData] = []
|
||||
@@ -0,0 +1,48 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import Confidence, ErrorType, SkyGrade, SkyType
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.v1.sky.protocol import BestTime, RankData, Res_Sky, Res_SkyRanking, SkyScoreData, SpotData
|
||||
from services.calc.sky_score import GRADE_LABEL
|
||||
from services.sky_service import SkyService
|
||||
|
||||
router = APIRouter(prefix="/v1/sky", tags=["sky"])
|
||||
|
||||
def _score(x: SkyScore) -> SkyScoreData:
|
||||
g = SkyGrade(x.grade)
|
||||
return SkyScoreData(
|
||||
day=x.score_date, sky_type=SkyType(x.sky_type), score=x.score, grade=g, grade_label=GRADE_LABEL[g],
|
||||
confidence=Confidence(x.confidence), best_times=[BestTime(**b) for b in x.best_times],
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Sky, response_model_exclude_none=True, summary="노을·일출 점수, 3컷, 가까운 명소, 앞으로 3일")
|
||||
async def get_sky(region: str = Query(..., description="구 행정코드"), service: SkyService = Depends()) -> Res_Sky:
|
||||
err, view = await service.view(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Sky(result=error_info(err))
|
||||
return Res_Sky(
|
||||
region_code=view.region.code, sunset_azimuth=view.sunset_azimuth,
|
||||
sunset=_score(view.sunset) if view.sunset else None, sunrise=_score(view.sunrise) if view.sunrise else None,
|
||||
days=[_score(x) for x in view.days],
|
||||
spots=[
|
||||
SpotData(no=i + 1, name=s.spot.name, description=s.spot.description, lat=float(s.spot.lat), lon=float(s.spot.lon), distance_km=s.distance_km)
|
||||
for i, s in enumerate(view.spots)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ranking", response_model=Res_SkyRanking, response_model_exclude_none=True, summary="전국 노을 순위 (대표 30곳)")
|
||||
async def get_sky_ranking(service: SkyService = Depends()) -> Res_SkyRanking:
|
||||
err, items = await service.ranking()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_SkyRanking(result=error_info(err))
|
||||
return Res_SkyRanking(
|
||||
day=now_kst().date(),
|
||||
items=[
|
||||
RankData(rank=i.rank, region_code=i.region.code, name=i.region.name, note=i.region.ranking_note, score=i.score.score, grade=SkyGrade(i.score.grade))
|
||||
for i in items
|
||||
],
|
||||
)
|
||||
Whitespace-only changes.
@@ -0,0 +1,76 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import AirGrade, RainType, Sky, SlotTone, WarningLevel, WarningType
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class WeatherSlot(WebPacketProtocol):
|
||||
at: datetime
|
||||
label: str
|
||||
temp_c: Optional[float] = None
|
||||
feels_c: Optional[float] = None
|
||||
sky: Optional[Sky] = None
|
||||
rain_type: Optional[RainType] = None
|
||||
rain_prob: Optional[int] = None
|
||||
icon: str
|
||||
tone: SlotTone
|
||||
note: str
|
||||
|
||||
|
||||
class Res_WeatherToday(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
region_name: Optional[str] = None
|
||||
day: Optional[date] = None
|
||||
issued_at: Optional[datetime] = None
|
||||
headline: Optional[str] = None
|
||||
slots: list[WeatherSlot] = []
|
||||
|
||||
|
||||
class RainHourData(WebPacketProtocol):
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
|
||||
|
||||
class Rain2h(WebPacketProtocol):
|
||||
will_rain: bool
|
||||
text: str
|
||||
hours: list[RainHourData] = []
|
||||
|
||||
|
||||
class CommuteData(WebPacketProtocol):
|
||||
label: str
|
||||
at: datetime
|
||||
icon: str
|
||||
temp_c: Optional[float] = None
|
||||
text: str
|
||||
|
||||
|
||||
class Tomorrow(WebPacketProtocol):
|
||||
text: str
|
||||
rain_from: Optional[datetime] = None
|
||||
commute: list[CommuteData] = []
|
||||
|
||||
|
||||
class AirData(WebPacketProtocol):
|
||||
station_name: str
|
||||
pm25: Optional[int] = None
|
||||
pm10: Optional[int] = None
|
||||
grade: Optional[AirGrade] = None
|
||||
measured_at: datetime
|
||||
text: Optional[str] = None
|
||||
|
||||
|
||||
class WarningData(WebPacketProtocol):
|
||||
warning_type: WarningType
|
||||
level: WarningLevel
|
||||
text: str
|
||||
|
||||
|
||||
class Res_WeatherNow(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
rain_2h: Optional[Rain2h] = None
|
||||
tomorrow: Optional[Tomorrow] = None
|
||||
air: Optional[AirData] = None
|
||||
warnings: Optional[list[WarningData]] = None
|
||||
@@ -0,0 +1,66 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST
|
||||
from router.v1.weather.protocol import (
|
||||
AirData,
|
||||
CommuteData,
|
||||
Rain2h,
|
||||
RainHourData,
|
||||
Res_WeatherNow,
|
||||
Res_WeatherToday,
|
||||
Tomorrow,
|
||||
WarningData,
|
||||
WeatherSlot,
|
||||
)
|
||||
from services.now_service import NowService
|
||||
from services.weather_service import Slot, WeatherService
|
||||
|
||||
router = APIRouter(prefix="/v1/weather", tags=["weather"])
|
||||
|
||||
|
||||
def _to_slot(s: Slot) -> WeatherSlot:
|
||||
data = WeatherSlot(at=s.at, label=f"{s.at.astimezone(KST).hour}시", icon=s.icon, tone=s.tone, note=s.note)
|
||||
if s.row is not None:
|
||||
data.temp_c, data.feels_c = float(s.row.temp_c), float(s.row.feels_c)
|
||||
data.sky, data.rain_type, data.rain_prob = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘 3시간 칸 날씨")
|
||||
async def get_weather_today(region: str = Query(..., description="구 행정코드"), service: WeatherService = Depends()) -> Res_WeatherToday:
|
||||
err, today = await service.today(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_WeatherToday(result=error_info(err))
|
||||
return Res_WeatherToday(
|
||||
region_code=today.region.code, region_name=today.region.name, day=today.day,
|
||||
issued_at=today.issued_at.astimezone(KST) if today.issued_at else None, headline=today.headline, slots=[_to_slot(s) for s in today.slots],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/now", response_model=Res_WeatherNow, response_model_exclude_none=True, summary="지금 비 올까: 2시간 비, 내일 출퇴근, 미세먼지, 특보")
|
||||
async def get_weather_now(region: str = Query(..., description="구 행정코드"), service: NowService = Depends()) -> Res_WeatherNow:
|
||||
err, now = await service.now(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_WeatherNow(result=error_info(err))
|
||||
res = Res_WeatherNow(
|
||||
region_code=now.region.code,
|
||||
rain_2h=Rain2h(
|
||||
will_rain=now.will_rain_2h, text=now.rain_2h_text,
|
||||
hours=[RainHourData(at=h.at.astimezone(KST), rain_type=h.rain_type, rain_mm=h.rain_mm) for h in now.rain_hours],
|
||||
),
|
||||
tomorrow=Tomorrow(
|
||||
text=now.tomorrow_text,
|
||||
rain_from=now.tomorrow_rain_from.astimezone(KST) if now.tomorrow_rain_from else None,
|
||||
commute=[CommuteData(label=c.label, at=c.at.astimezone(KST), icon=c.icon, temp_c=c.temp_c, text=c.text) for c in now.commute],
|
||||
),
|
||||
)
|
||||
if now.air is not None:
|
||||
res.air = AirData(
|
||||
station_name=now.air.station_name, pm25=now.air.pm25, pm10=now.air.pm10,
|
||||
grade=AirGrade(now.air.grade) if now.air.grade else None, measured_at=now.air.measured_at.astimezone(KST), text=now.air_text,
|
||||
)
|
||||
if now.warnings is not None:
|
||||
res.warnings = [WarningData(warning_type=w.warning_type, level=w.level, text=w.text) for w in now.warnings]
|
||||
return res
|
||||
Whitespace-only changes.
@@ -0,0 +1,57 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class DayData(WebPacketProtocol):
|
||||
day: date
|
||||
weekday: str
|
||||
holiday: Optional[str] = None
|
||||
icon: str
|
||||
temp_min_c: Optional[float] = None
|
||||
temp_max_c: Optional[float] = None
|
||||
headline: str
|
||||
summary: str
|
||||
pick: str
|
||||
rain_hours: Optional[list[int]] = None
|
||||
is_rainy: bool
|
||||
|
||||
|
||||
class Res_Week(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
days: list[DayData] = []
|
||||
|
||||
|
||||
class PlaceData(WebPacketProtocol):
|
||||
place_id: int
|
||||
area: str
|
||||
name: str
|
||||
is_outdoor: bool
|
||||
icon: str
|
||||
reason: str
|
||||
best_time: str
|
||||
is_good: bool
|
||||
|
||||
|
||||
class Res_PlaceList(Res_WebPacketProtocol):
|
||||
areas: list[str] = []
|
||||
rainy: Optional[bool] = None
|
||||
places: list[PlaceData] = []
|
||||
|
||||
|
||||
class EventData(WebPacketProtocol):
|
||||
event_id: int
|
||||
name: str
|
||||
place_name: str
|
||||
icon: str
|
||||
start_date: date
|
||||
end_date: date
|
||||
is_confirmed: bool
|
||||
status: str
|
||||
status_label: str
|
||||
fit: Optional[str] = None
|
||||
|
||||
|
||||
class Res_EventList(Res_WebPacketProtocol):
|
||||
events: list[EventData] = []
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.v1.week.protocol import DayData, EventData, PlaceData, Res_EventList, Res_PlaceList, Res_Week
|
||||
from services.week_service import WeekService
|
||||
|
||||
router = APIRouter(prefix="/v1/week", tags=["week"])
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Week, response_model_exclude_none=True, summary="7일 날씨와 그날 추천")
|
||||
async def get_week(region: str = Query(..., description="구 행정코드"), service: WeekService = Depends()) -> Res_Week:
|
||||
err, days = await service.week(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Week(result=error_info(err))
|
||||
return Res_Week(region_code=region, days=[
|
||||
DayData(**{**d.__dict__, "rain_hours": list(d.rain_hours) if d.rain_hours else None}) for d in days
|
||||
])
|
||||
|
||||
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소")
|
||||
async def list_places(
|
||||
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
||||
service: WeekService = Depends(),
|
||||
) -> Res_PlaceList:
|
||||
target = day or now_kst().date()
|
||||
err, items, areas = await service.places(region, target, area)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_PlaceList(result=error_info(err))
|
||||
rainy = any(not i.place.is_outdoor and i.is_good for i in items)
|
||||
return Res_PlaceList(areas=areas, rainy=rainy, places=[
|
||||
PlaceData(
|
||||
place_id=i.place.place_id, area=i.place.area, name=i.place.name, is_outdoor=i.place.is_outdoor, icon=i.place.icon,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good,
|
||||
)
|
||||
for i in items
|
||||
])
|
||||
|
||||
|
||||
@router.get("/event/list", response_model=Res_EventList, response_model_exclude_none=True, summary="앞으로 30일 축제·행사")
|
||||
async def list_events(region: str = Query(...), area: Optional[str] = Query(None), service: WeekService = Depends()) -> Res_EventList:
|
||||
err, items = await service.events(region, area)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_EventList(result=error_info(err))
|
||||
return Res_EventList(events=[
|
||||
EventData(
|
||||
event_id=i.event.event_id, name=i.event.name, place_name=i.event.place_name, icon=i.event.icon, start_date=i.event.start_date,
|
||||
end_date=i.event.end_date, is_confirmed=i.event.is_confirmed, status=i.status, status_label=i.status_label, fit=i.fit,
|
||||
)
|
||||
for i in items
|
||||
])
|
||||
Whitespace-only changes.
@@ -0,0 +1,47 @@
|
||||
import httpx
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.air_crud import AirCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from services.external.airkorea import fetch_stations, parse_stations
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
|
||||
_CLEANUP_SQL = [
|
||||
"DELETE FROM public.weather_hourly WHERE forecast_at < now() - interval '7 days'",
|
||||
"DELETE FROM public.weather_daily WHERE forecast_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
||||
"DELETE FROM public.sun_time WHERE sun_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
||||
"DELETE FROM public.cloud_hourly WHERE forecast_at < now() - interval '2 days'",
|
||||
"DELETE FROM public.event WHERE end_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 30",
|
||||
]
|
||||
|
||||
|
||||
async def cleanup_old_rows() -> ErrorType:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s, q=q: s.execute(text(q)) for q in _CLEANUP_SQL])
|
||||
LOG.info(f"[scheduler] cleanup_old_rows: {err.name}")
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_air_stations() -> ErrorType:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
rows = parse_stations(await fetch_stations(client))
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[scheduler] refresh_air_stations: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: AirCRUD().replace_stations(s, rows)])
|
||||
LOG.info(f"[scheduler] refresh_air_stations {len(rows)}: {err.name}")
|
||||
return err
|
||||
|
||||
|
||||
|
||||
async def build_today_feed() -> ErrorType:
|
||||
"""그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
||||
await clear_feed_cache()
|
||||
return err
|
||||
Whitespace-only changes.
@@ -0,0 +1,27 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
DEFAULT_OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "openapi.json")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""서버를 띄우지 않고 OpenAPI 스펙을 파일로 뽑는다 (프론트 orval 입력)."""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-o", "--out", default=DEFAULT_OUT)
|
||||
args = parser.parse_args()
|
||||
|
||||
import router.router
|
||||
|
||||
spec = router.router.app.openapi()
|
||||
with open(args.out, "w", encoding="utf-8") as f:
|
||||
json.dump(spec, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
print(f"{args.out} ({len(spec['paths'])} paths)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,94 @@
|
||||
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}
|
||||
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": int(r["sort_order"])}
|
||||
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()))
|
||||
@@ -0,0 +1,102 @@
|
||||
[
|
||||
{
|
||||
"code": "maple",
|
||||
"category": 1,
|
||||
"title": "설악산 첫 단풍, 절정은 언제?",
|
||||
"read_minutes": 3,
|
||||
"icon": "maple",
|
||||
"show_from": "2026-09-20",
|
||||
"show_until": "2026-10-25",
|
||||
"body": [
|
||||
"설악산은 해마다 9월 말에서 10월 초 사이에 정상부터 단풍이 들기 시작해요.",
|
||||
"산 전체의 80%가 물드는 절정은 보통 첫 단풍 뒤 2주쯤, 10월 중순이에요. 서울 근교 산은 10월 말부터예요.",
|
||||
"(예년 기준 정보예요. 올해 시기는 산림청 단풍 예보로 확인하세요.)"
|
||||
],
|
||||
"sort_order": 1
|
||||
},
|
||||
{
|
||||
"code": "reed",
|
||||
"category": 1,
|
||||
"title": "하늘공원 억새가 반짝이는 시간",
|
||||
"read_minutes": 2,
|
||||
"icon": "sheaf",
|
||||
"show_from": "2026-09-25",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
"하늘공원 억새는 9월 말부터 피기 시작해 10월 중순에 가장 풍성해요.",
|
||||
"해 질 녘 역광으로 볼 때 은빛으로 가장 반짝여요. 노을 점수가 높은 날 같이 보면 좋아요."
|
||||
],
|
||||
"sort_order": 2
|
||||
},
|
||||
{
|
||||
"code": "frost",
|
||||
"category": 1,
|
||||
"title": "대관령 첫서리, 서울은 한 달 뒤",
|
||||
"read_minutes": 2,
|
||||
"icon": "snow",
|
||||
"show_from": "2026-10-01",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
"강원 산간은 10월 초중순이면 첫서리가 내려요. 서울은 보통 10월 말에서 11월 초예요.",
|
||||
"주말에 강원도로 간다면 아침 기온이 한 자릿수로 내려가니 두꺼운 겉옷을 챙기세요."
|
||||
],
|
||||
"sort_order": 3
|
||||
},
|
||||
{
|
||||
"code": "howgak",
|
||||
"category": 3,
|
||||
"title": "각 점수는 이렇게 매겨요",
|
||||
"read_minutes": 3,
|
||||
"icon": "bulb",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"모든 각은 기온·비·바람·습도·공기·시간대 6가지 요소로 계산해요.",
|
||||
"각마다 중요한 요소가 달라요. 야장각은 기온 30%·비 25%, 환기는 공기가 45%, 별보기는 시간대(달 밝기)가 45%예요.",
|
||||
"비가 많이 오거나 바람이 너무 세면, 다른 점수와 상관없이 바로 0점이 되는 조건도 있어요."
|
||||
],
|
||||
"sort_order": 4
|
||||
},
|
||||
{
|
||||
"code": "di",
|
||||
"category": 2,
|
||||
"title": "불쾌지수 67은 어느 정도일까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "thermo",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"불쾌지수는 기온과 습도로 계산해요. 68 미만이면 대부분 쾌적, 75를 넘으면 절반 정도가 불쾌하다고 느껴요.",
|
||||
"같은 21°라도 습도가 높으면 더 끈적하게 느껴져요."
|
||||
],
|
||||
"sort_order": 5
|
||||
},
|
||||
{
|
||||
"code": "sunset",
|
||||
"category": 2,
|
||||
"title": "노을은 왜 해 지고 15분 뒤가 더 붉을까?",
|
||||
"read_minutes": 3,
|
||||
"icon": "sunset",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"해가 지평선 아래로 내려가면 햇빛이 높은 구름 아래쪽을 비춰요. 이때 구름이 붉게 물들어요.",
|
||||
"그래서 높고 얇은 구름이 서쪽에 깔린 날, 해 지고 10~20분 뒤에 가장 붉어요. 날씨각 노을 점수는 이 구름을 봐요."
|
||||
],
|
||||
"sort_order": 6
|
||||
},
|
||||
{
|
||||
"code": "umbrella",
|
||||
"category": 2,
|
||||
"title": "비 확률 30%면 우산을 챙겨야 할까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "umbrella",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
"비 확률 30%는 같은 예보가 10번 나왔을 때 3번쯤 비가 왔다는 뜻이에요.",
|
||||
"접는 우산이 가볍다면 30%부터, 무겁다면 60%부터 챙기는 걸 추천해요."
|
||||
],
|
||||
"sort_order": 7
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
region_name,area,name,place_name,icon,start_date,end_date,source_url
|
||||
|
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,11 @@
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10
|
||||
|
@@ -0,0 +1,31 @@
|
||||
name,note
|
||||
충남 태안군,서해 수평선
|
||||
인천 제물포구,월미도
|
||||
전남 목포시,유달산
|
||||
서울 마포구,망원한강공원
|
||||
전북 군산시,선유도
|
||||
제주 제주시,애월
|
||||
경기 수원시 팔달구,화성 서장대
|
||||
전남 여수시,돌산
|
||||
충남 보령시,대천해수욕장
|
||||
전북 부안군,채석강
|
||||
전남 신안군,증도
|
||||
전남 진도군,세방낙조
|
||||
제주 서귀포시,송악산
|
||||
경기 김포시,애기봉
|
||||
서울 강남구,도심 스카이라인
|
||||
경남 통영시,달아공원
|
||||
경남 남해군,설리해변
|
||||
부산 해운대구,동백섬
|
||||
울산 동구,대왕암
|
||||
강원 강릉시,경포대
|
||||
강원 속초시,영금정
|
||||
강원 춘천시,소양강
|
||||
충북 청주시 상당구,상당산성
|
||||
대전 서구,갑천
|
||||
세종 세종특별자치시,금강
|
||||
경북 안동시,월영교
|
||||
경북 포항시 남구,호미곶
|
||||
대구 수성구,수성못
|
||||
전북 전주시 완산구,한옥마을
|
||||
광주 서구,풍암호수
|
||||
|
@@ -0,0 +1,257 @@
|
||||
code,name,short_name,lat,lon,nx,ny,warning_zone_code,mid_land_code,mid_temp_code
|
||||
1111000000,서울 종로구,종로구,37.57038,126.98164,60,127,L1100200,11B00000,11B10101
|
||||
1114000000,서울 중구,중구,37.561,126.99964,60,127,L1100200,11B00000,11B10101
|
||||
1117000000,서울 용산구,용산구,37.53609,126.96752,60,126,L1100200,11B00000,11B10101
|
||||
1120000000,서울 성동구,성동구,37.56061,127.039,61,127,L1100200,11B00000,11B10101
|
||||
1121500000,서울 광진구,광진구,37.53574,127.08453,62,126,L1100200,11B00000,11B10101
|
||||
1123000000,서울 동대문구,동대문구,37.57162,127.04214,61,127,L1100200,11B00000,11B10101
|
||||
1126000000,서울 중랑구,중랑구,37.60381,127.09478,62,128,L1100200,11B00000,11B10101
|
||||
1129000000,서울 성북구,성북구,37.58638,127.02033,61,127,L1100200,11B00000,11B10101
|
||||
1130500000,서울 강북구,강북구,37.63696,127.02772,61,128,L1100200,11B00000,11B10101
|
||||
1132000000,서울 도봉구,도봉구,37.66583,127.04952,61,129,L1100200,11B00000,11B10101
|
||||
1135000000,서울 노원구,노원구,37.65146,127.05839,61,129,L1100200,11B00000,11B10101
|
||||
1138000000,서울 은평구,은평구,37.59997,126.93124,59,127,L1100400,11B00000,11B10101
|
||||
1141000000,서울 서대문구,서대문구,37.57637,126.9389,59,127,L1100400,11B00000,11B10101
|
||||
1144000000,서울 마포구,마포구,37.56071,126.91053,59,127,L1100400,11B00000,11B10101
|
||||
1147000000,서울 양천구,양천구,37.51423,126.86871,58,126,L1100300,11B00000,11B10101
|
||||
1150000000,서울 강서구,강서구,37.54816,126.85168,58,126,L1100300,11B00000,11B10101
|
||||
1153000000,서울 구로구,구로구,37.49265,126.8896,58,125,L1100300,11B00000,11B10101
|
||||
1154500000,서울 금천구,금천구,37.44911,126.9042,59,124,L1100300,11B00000,11B10101
|
||||
1156000000,서울 영등포구,영등포구,37.52361,126.89834,58,126,L1100300,11B00000,11B10101
|
||||
1159000000,서울 동작구,동작구,37.50966,126.94158,59,125,L1100300,11B00000,11B10101
|
||||
1162000000,서울 관악구,관악구,37.47539,126.95384,59,125,L1100300,11B00000,11B10101
|
||||
1165000000,서울 서초구,서초구,37.48079,127.03481,61,125,L1100100,11B00000,11B10101
|
||||
1168000000,서울 강남구,강남구,37.51458,127.04956,61,126,L1100100,11B00000,11B10101
|
||||
1171000000,서울 송파구,송파구,37.51176,127.10793,62,126,L1100100,11B00000,11B10101
|
||||
1174000000,서울 강동구,강동구,37.52737,127.12586,62,126,L1100100,11B00000,11B10101
|
||||
1211000000,전남 목포시,목포시,34.80879,126.39442,50,67,L1052100,11F20000,21F20801
|
||||
1213000000,전남 여수시,여수시,34.75731,127.66439,73,66,L1051000,11F20000,11F20401
|
||||
1215000000,전남 순천시,순천시,34.94761,127.48933,70,70,L1051200,11F20000,11F20603
|
||||
1217000000,전남 나주시,나주시,35.01284,126.71287,56,71,L1052800,11F20000,11F20503
|
||||
1219000000,전남 광양시,광양시,34.93754,127.69818,73,70,L1051100,11F20000,11F20402
|
||||
1221000000,광주 동구,동구,35.1431,126.92518,60,74,L1130000,11F20000,11F20501
|
||||
1224000000,광주 서구,서구,35.14948,126.89341,59,74,L1130000,11F20000,11F20501
|
||||
1227000000,광주 남구,남구,35.11904,126.91014,59,73,L1130000,11F20000,11F20501
|
||||
1230000000,광주 북구,북구,35.17112,126.91412,59,75,L1130000,11F20000,11F20501
|
||||
1233000000,광주 광산구,광산구,35.13643,126.79579,57,74,L1130000,11F20000,11F20501
|
||||
1271000000,전남 담양군,담양군,35.31813,126.99016,61,78,L1050300,11F20000,11F20504
|
||||
1272000000,전남 곡성군,곡성군,35.27896,127.29411,66,77,L1052900,11F20000,11F20602
|
||||
1273000000,전남 구례군,구례군,35.19946,127.46493,69,75,L1053000,11F20000,11F20601
|
||||
1274000000,전남 고흥군,고흥군,34.60807,127.28706,66,62,L1053100,11F20000,11F20403
|
||||
1275000000,전남 보성군,보성군,34.76833,127.08209,62,66,L1050900,11F20000,11F20404
|
||||
1276000000,전남 화순군,화순군,35.06148,126.98857,61,72,L1050700,11F20000,11F20505
|
||||
1277000000,전남 장흥군,장흥군,34.67853,126.90911,59,64,L1051300,11F20000,11F20304
|
||||
1278000000,전남 강진군,강진군,34.63891,126.7692,57,63,L1051400,11F20000,11F20303
|
||||
1279000000,전남 해남군,해남군,34.57044,126.60129,54,61,L1053200,11F20000,11F20302
|
||||
1280000000,전남 영암군,영암군,34.79699,126.69862,56,66,L1051700,11F20000,21F20802
|
||||
1281000000,전남 무안군,무안군,34.98737,126.4837,52,71,L1053400,11F20000,21F20804
|
||||
1282000000,전남 함평군,함평군,35.06274,126.51862,52,72,L1051900,11F20000,21F20101
|
||||
1283000000,전남 영광군,영광군,35.27417,126.51409,52,77,L1052700,11F20000,21F20102
|
||||
1284000000,전남 장성군,장성군,35.29881,126.78697,57,77,L1050600,11F20000,11F20502
|
||||
1285000000,전남 완도군,완도군,34.30785,126.7571,57,56,L1053300,11F20000,11F20301
|
||||
1286000000,전남 진도군,진도군,34.48375,126.26554,48,59,L1052300,11F20000,21F20201
|
||||
1287000000,전남 신안군,신안군,34.78981,126.38173,50,66,L1052200,11F20000,21F20803
|
||||
2611000000,부산 중구,중구,35.10322,129.03451,97,74,L1150000,11H20000,11H20201
|
||||
2614000000,부산 서구,서구,35.09484,129.02638,97,74,L1150000,11H20000,11H20201
|
||||
2617000000,부산 동구,동구,35.13589,129.05918,98,75,L1150000,11H20000,11H20201
|
||||
2620000000,부산 영도구,영도구,35.08812,129.07019,98,74,L1150000,11H20000,11H20201
|
||||
2623000000,부산 부산진구,부산진구,35.15995,129.05532,97,75,L1150000,11H20000,11H20201
|
||||
2626000000,부산 동래구,동래구,35.20187,129.08586,98,76,L1150000,11H20000,11H20201
|
||||
2629000000,부산 남구,남구,35.13341,129.0865,98,75,L1150000,11H20000,11H20201
|
||||
2632000000,부산 북구,북구,35.19418,128.99247,96,76,L1150000,11H20000,11H20201
|
||||
2635000000,부산 해운대구,해운대구,35.16002,129.16581,99,75,L1150000,11H20000,11H20201
|
||||
2638000000,부산 사하구,사하구,35.10143,128.97704,96,74,L1150000,11H20000,11H20201
|
||||
2641000000,부산 금정구,금정구,35.24008,129.09432,98,77,L1150000,11H20000,11H20201
|
||||
2644000000,부산 강서구,강서구,35.20916,128.98291,96,76,L1150000,11H20000,11H20201
|
||||
2647000000,부산 연제구,연제구,35.17319,129.08208,98,76,L1150000,11H20000,11H20201
|
||||
2650000000,부산 수영구,수영구,35.14247,129.11538,99,75,L1150000,11H20000,11H20201
|
||||
2653000000,부산 사상구,사상구,35.14947,128.99333,96,75,L1150000,11H20000,11H20201
|
||||
2671000000,부산 기장군,기장군,35.24135,129.22448,100,77,L1150000,11H20000,11H20201
|
||||
2711000000,대구 중구,중구,35.86629,128.6084,89,90,L1140000,11H10000,11H10701
|
||||
2714000000,대구 동구,동구,35.88362,128.63771,90,91,L1140000,11H10000,11H10701
|
||||
2717000000,대구 서구,서구,35.86879,128.56141,88,90,L1140000,11H10000,11H10701
|
||||
2720000000,대구 남구,남구,35.84298,128.5998,89,90,L1140000,11H10000,11H10701
|
||||
2723000000,대구 북구,북구,35.8827,128.58502,89,91,L1140000,11H10000,11H10701
|
||||
2726000000,대구 수성구,수성구,35.85521,128.63287,89,90,L1140000,11H10000,11H10701
|
||||
2729000000,대구 달서구,달서구,35.82693,128.53506,88,90,L1140000,11H10000,11H10701
|
||||
2771000000,대구 달성군,달성군,35.77168,128.43327,86,88,L1140000,11H10000,11H10701
|
||||
2772000000,대구 군위군,군위군,36.24,128.57508,88,99,L1140000,11H10000,11H10701
|
||||
2812500000,인천 제물포구,제물포구,37.47093,126.62357,54,125,L1110000,11B00000,11B20201
|
||||
2815500000,인천 영종구,영종구,37.48977,126.55996,53,125,L1110000,11B00000,11B20201
|
||||
2817700000,인천 미추홀구,미추홀구,37.46068,126.65269,54,124,L1110000,11B00000,11B20201
|
||||
2818500000,인천 연수구,연수구,37.40712,126.68044,55,123,L1110000,11B00000,11B20201
|
||||
2820000000,인천 남동구,남동구,37.44452,126.7338,56,124,L1110000,11B00000,11B20201
|
||||
2823700000,인천 부평구,부평구,37.50427,126.7241,55,125,L1110000,11B00000,11B20201
|
||||
2824500000,인천 계양구,계양구,37.53479,126.73975,56,126,L1110000,11B00000,11B20201
|
||||
2827500000,인천 서해구,서해구,37.54269,126.6782,55,126,L1110000,11B00000,11B20201
|
||||
2829000000,인천 검단구,검단구,37.59153,126.68157,55,127,L1110000,11B00000,11B20201
|
||||
2871000000,인천 강화군,강화군,37.74386,126.49,51,130,L1110000,11B00000,11B20201
|
||||
2872000000,인천 옹진군,옹진군,37.44372,126.63889,54,124,L1110000,11B00000,11B20201
|
||||
3011000000,대전 동구,동구,36.32413,127.43485,68,100,L1030100,11C20000,11C20401
|
||||
3014000000,대전 중구,중구,36.32263,127.42311,68,100,L1030100,11C20000,11C20401
|
||||
3017000000,대전 서구,서구,36.35248,127.38577,67,100,L1030100,11C20000,11C20401
|
||||
3020000000,대전 유성구,유성구,36.35937,127.35834,67,101,L1030100,11C20000,11C20401
|
||||
3023000000,대전 대덕구,대덕구,36.34379,127.41769,68,100,L1030100,11C20000,11C20401
|
||||
3111000000,울산 중구,중구,35.56634,129.33488,102,84,L1160000,11H20000,11H20101
|
||||
3114000000,울산 남구,남구,35.54076,129.33239,102,84,L1160000,11H20000,11H20101
|
||||
3117000000,울산 동구,동구,35.50189,129.41895,104,83,L1160000,11H20000,11H20101
|
||||
3120000000,울산 북구,북구,35.57969,129.36354,103,85,L1160000,11H20000,11H20101
|
||||
3171000000,울산 울주군,울주군,35.53074,129.29716,101,84,L1160000,11H20000,11H20101
|
||||
3611000000,세종 세종특별자치시,세종특별자치시,36.48001,127.28907,66,103,L1170000,11C20000,11C20404
|
||||
4111100000,경기 수원시 장안구,수원시 장안구,37.30101,127.01222,60,121,L1011900,11B00000,11B20601
|
||||
4111300000,경기 수원시 권선구,수원시 권선구,37.25473,126.97407,60,120,L1011900,11B00000,11B20601
|
||||
4111500000,경기 수원시 팔달구,수원시 팔달구,37.2831,127.03783,61,121,L1011900,11B00000,11B20601
|
||||
4111700000,경기 수원시 영통구,수원시 영통구,37.25631,127.04863,61,120,L1011900,11B00000,11B20601
|
||||
4113100000,경기 성남시 수정구,성남시 수정구,37.44749,127.14772,63,124,L1012000,11B00000,11B20605
|
||||
4113300000,경기 성남시 중원구,성남시 중원구,37.42767,127.13942,63,124,L1012000,11B00000,11B20605
|
||||
4113500000,경기 성남시 분당구,성남시 분당구,37.37997,127.12102,62,123,L1012000,11B00000,11B20605
|
||||
4115000000,경기 의정부시,의정부시,37.73529,127.03584,61,130,L1011700,11B00000,11B20301
|
||||
4117100000,경기 안양시 만안구,안양시 만안구,37.38378,126.9345,59,123,L1012100,11B00000,11B20602
|
||||
4117300000,경기 안양시 동안구,안양시 동안구,37.3897,126.95336,59,123,L1012100,11B00000,11B20602
|
||||
4119200000,경기 부천시 원미구,부천시 원미구,37.49659,126.787,57,125,L1010600,11B00000,11B20204
|
||||
4119400000,경기 부천시 소사구,부천시 소사구,37.48004,126.79994,57,125,L1010600,11B00000,11B20204
|
||||
4119600000,경기 부천시 오정구,부천시 오정구,37.52835,126.79581,57,126,L1010600,11B00000,11B20204
|
||||
4121000000,경기 광명시,광명시,37.47575,126.86671,58,125,L1010200,11B00000,11B10103
|
||||
4122000000,경기 평택시,평택시,36.98944,127.11466,62,114,L1012500,11B00000,11B20606
|
||||
4125000000,경기 동두천시,동두천시,37.90092,127.06265,61,134,L1011100,11B00000,11B20401
|
||||
4127100000,경기 안산시 상록구,안산시 상록구,37.29852,126.84682,58,121,L1010400,11B00000,11B20203
|
||||
4127300000,경기 안산시 단원구,안산시 단원구,37.31673,126.81442,57,121,L1010400,11B00000,11B20203
|
||||
4128100000,경기 고양시 덕양구,고양시 덕양구,37.63458,126.8342,57,128,L1011500,11B00000,11B20302
|
||||
4128500000,경기 고양시 일산동구,고양시 일산동구,37.65591,126.77706,56,129,L1011500,11B00000,11B20302
|
||||
4128700000,경기 고양시 일산서구,고양시 일산서구,37.67249,126.75278,56,129,L1011500,11B00000,11B20302
|
||||
4129000000,경기 과천시,과천시,37.42637,126.9898,60,124,L1010300,11B00000,11B10102
|
||||
4131000000,경기 구리시,구리시,37.59163,127.13186,62,127,L1012200,11B00000,11B20501
|
||||
4136000000,경기 남양주시,남양주시,37.63318,127.21863,64,128,L1012300,11B00000,11B20502
|
||||
4137000000,경기 오산시,오산시,37.14691,127.07964,62,118,L1012400,11B00000,11B20603
|
||||
4139000000,경기 시흥시,시흥시,37.37732,126.80508,57,123,L1010500,11B00000,11B20202
|
||||
4141000000,경기 군포시,군포시,37.35866,126.9375,59,122,L1012600,11B00000,11B20610
|
||||
4143000000,경기 의왕시,의왕시,37.34195,126.97039,60,122,L1012700,11B00000,11B20609
|
||||
4145000000,경기 하남시,하남시,37.5365,127.217,64,126,L1012800,11B00000,11B20504
|
||||
4146100000,경기 용인시 처인구,용인시 처인구,37.23148,127.20384,64,119,L1013800,11B00000,11B20612
|
||||
4146300000,경기 용인시 기흥구,용인시 기흥구,37.2776,127.11679,62,120,L1013800,11B00000,11B20612
|
||||
4146500000,경기 용인시 수지구,용인시 수지구,37.31939,127.1001,62,121,L1013800,11B00000,11B20612
|
||||
4148000000,경기 파주시,파주시,37.75708,126.78195,56,131,L1013700,11B00000,11B20305
|
||||
4150000000,경기 이천시,이천시,37.27544,127.44322,68,121,L1013000,11B00000,11B20701
|
||||
4155000000,경기 안성시,안성시,37.00518,127.28184,65,115,L1013100,11B00000,11B20611
|
||||
4157000000,경기 김포시,김포시,37.61246,126.71778,55,128,L1010700,11B00000,11B20102
|
||||
4159100000,경기 화성시 만세구,화성시 만세구,37.1377,126.92566,59,117,L1013200,11B00000,11B20604
|
||||
4159300000,경기 화성시 효행구,화성시 효행구,37.20918,126.95915,60,119,L1013200,11B00000,11B20604
|
||||
4159500000,경기 화성시 병점구,화성시 병점구,37.20875,127.0359,61,119,L1013200,11B00000,11B20604
|
||||
4159700000,경기 화성시 동탄구,화성시 동탄구,37.19724,127.09687,62,119,L1013200,11B00000,11B20604
|
||||
4161000000,경기 광주시,광주시,37.41451,127.25779,65,123,L1013400,11B00000,11F20501
|
||||
4163000000,경기 양주시,양주시,37.78245,127.04782,61,131,L1011600,11B00000,11B20304
|
||||
4165000000,경기 포천시,포천시,37.89216,127.20242,64,134,L1011300,11B00000,11B20403
|
||||
4167000000,경기 여주시,여주시,37.29536,127.63962,71,121,L1013900,11B00000,11B20703
|
||||
4180000000,경기 연천군,연천군,38.09336,127.07707,61,138,L1011200,11B00000,11B20402
|
||||
4182000000,경기 가평군,가평군,37.82883,127.51178,69,133,L1011400,11B00000,11B20404
|
||||
4183000000,경기 양평군,양평군,37.48894,127.48989,69,125,L1014400,11B00000,11B20503
|
||||
4311100000,충북 청주시 상당구,청주시 상당구,36.584,127.51173,69,106,L1041400,11C10000,11C10301
|
||||
4311200000,충북 청주시 서원구,청주시 서원구,36.63726,127.48329,69,107,L1041400,11C10000,11C10301
|
||||
4311300000,충북 청주시 흥덕구,청주시 흥덕구,36.6182,127.35942,67,106,L1041400,11C10000,11C10301
|
||||
4311400000,충북 청주시 청원구,청주시 청원구,36.64431,127.48766,69,107,L1041400,11C10000,11C10301
|
||||
4313000000,충북 충주시,충주시,36.98818,127.92814,76,114,L1040800,11C10000,11C10101
|
||||
4315000000,충북 제천시,제천시,37.12977,128.19315,81,118,L1040900,11C10000,11C10201
|
||||
4372000000,충북 보은군,보은군,36.48653,127.73161,73,103,L1040300,11C10000,11C10302
|
||||
4373000000,충북 옥천군,옥천군,36.30355,127.57363,71,99,L1040600,11C10000,11C10403
|
||||
4374000000,충북 영동군,영동군,36.17206,127.78561,74,97,L1040700,11C10000,11C10402
|
||||
4374500000,충북 증평군,증평군,36.78218,127.58329,71,110,L1041300,11C10000,11C10304
|
||||
4375000000,충북 진천군,진천군,36.85254,127.43764,68,111,L1041000,11C10000,11C10102
|
||||
4376000000,충북 괴산군,괴산군,36.81243,127.78883,74,111,L1040400,11C10000,11C10303
|
||||
4377000000,충북 음성군,음성군,36.93741,127.69262,72,113,L1041100,11C10000,11C10103
|
||||
4380000000,충북 단양군,단양군,36.98178,128.36784,84,115,L1041200,11C10000,11C10202
|
||||
4413100000,충남 천안시 동남구,천안시 동남구,36.80412,127.15247,63,110,L1030200,11C20000,11C20301
|
||||
4413300000,충남 천안시 서북구,천안시 서북구,36.87556,127.1572,63,112,L1030200,11C20000,11C20301
|
||||
4415000000,충남 공주시,공주시,36.44361,127.12112,63,102,L1030300,11C20000,11C20402
|
||||
4418000000,충남 보령시,보령시,36.33058,126.61489,54,100,L1031900,11C20000,11C20201
|
||||
4420000000,충남 아산시,아산시,36.78711,127.00464,60,110,L1030400,11C20000,11C20302
|
||||
4421000000,충남 서산시,서산시,36.7821,126.45216,51,110,L1031300,11C20000,11C20101
|
||||
4423000000,충남 논산시,논산시,36.1842,127.10091,62,97,L1030500,11C20000,11C20602
|
||||
4425000000,충남 계룡시,계룡시,36.27184,127.25093,65,99,L1031700,11C20000,11C20403
|
||||
4427000000,충남 당진시,당진시,36.89075,126.63025,54,112,L1031200,11C20000,11C20103
|
||||
4471000000,충남 금산군,금산군,36.10587,127.49031,69,95,L1030600,11C20000,11C20601
|
||||
4476000000,충남 부여군,부여군,36.27282,126.91186,59,99,L1030800,11C20000,11C20501
|
||||
4477000000,충남 서천군,서천군,36.07741,126.69389,55,94,L1031500,11C20000,11C20202
|
||||
4479000000,충남 청양군,청양군,36.45627,126.80426,57,103,L1030900,11C20000,11C20502
|
||||
4480000000,충남 홍성군,홍성군,36.59836,126.66291,55,106,L1032000,11C20000,11C20104
|
||||
4481000000,충남 예산군,예산군,36.67981,126.85087,58,107,L1031000,11C20000,11C20303
|
||||
4482500000,충남 태안군,태안군,36.74267,126.29998,48,109,L1031100,11C20000,11C20102
|
||||
4711100000,경북 포항시 남구,포항시 남구,36.00569,129.36167,102,94,L1072400,11H10000,11H10201
|
||||
4711300000,경북 포항시 북구,포항시 북구,36.03885,129.36791,102,95,L1072400,11H10000,11H10201
|
||||
4713000000,경북 경주시,경주시,35.85317,129.22702,100,91,L1073100,11H10000,11H10202
|
||||
4715000000,경북 김천시,김천시,36.1369,128.1158,80,96,L1072600,11H10000,11H10601
|
||||
4717000000,경북 안동시,안동시,36.56546,128.73162,91,106,L1072700,11H10000,11H10501
|
||||
4719000000,경북 구미시,구미시,36.11655,128.34678,84,96,L1070300,11H10000,11H10602
|
||||
4721000000,경북 영주시,영주시,36.80294,128.62634,89,111,L1071600,11H10000,11H10401
|
||||
4723000000,경북 영천시,영천시,35.97005,128.94078,95,93,L1070400,11H10000,11H10702
|
||||
4725000000,경북 상주시,상주시,36.40797,128.16126,81,102,L1071200,11H10000,11H10302
|
||||
4728000000,경북 문경시,문경시,36.58363,128.18902,81,106,L1071300,11H10000,11H10301
|
||||
4729000000,경북 경산시,경산시,35.82209,128.74346,91,90,L1070500,11H10000,11H10703
|
||||
4773000000,경북 의성군,의성군,36.34976,128.69936,90,101,L1071700,11H10000,11H10502
|
||||
4775000000,경북 청송군,청송군,36.43329,129.0594,96,103,L1071800,11H10000,11H10503
|
||||
4776000000,경북 영양군,영양군,36.66427,129.11462,97,108,L1072800,11H10000,11H10403
|
||||
4777000000,경북 영덕군,영덕군,36.4121,129.36836,102,103,L1072200,11H10000,11H10102
|
||||
4782000000,경북 청도군,청도군,35.64431,128.7362,91,86,L1070700,11H10000,11H10704
|
||||
4783000000,경북 고령군,고령군,35.72299,128.26502,83,87,L1070800,11H10000,11H10604
|
||||
4784000000,경북 성주군,성주군,35.91915,128.28299,83,91,L1070900,11H10000,11H10605
|
||||
4785000000,경북 칠곡군,칠곡군,35.99255,128.4038,85,93,L1071000,11H10000,11H10705
|
||||
4790000000,경북 예천군,예천군,36.65495,128.45502,86,107,L1071400,11H10000,11H10303
|
||||
4792000000,경북 봉화군,봉화군,36.89026,128.73487,90,113,L1072900,11H10000,11H10402
|
||||
4793000000,경북 울진군,울진군,36.99019,129.40279,102,115,L1073000,11H10000,11H10101
|
||||
4794000000,경북 울릉군,울릉군,37.48058,130.90379,127,127,L1072100,11H10000,11E00101
|
||||
4812100000,경남 창원시 의창구,창원시 의창구,35.254,128.64015,90,77,L1080600,11H20000,11H20301
|
||||
4812300000,경남 창원시 성산구,창원시 성산구,35.19838,128.70294,91,76,L1080600,11H20000,11H20301
|
||||
4812500000,경남 창원시 마산합포구,창원시 마산합포구,35.19687,128.56786,89,76,L1080600,11H20000,11H20301
|
||||
4812700000,경남 창원시 마산회원구,창원시 마산회원구,35.22093,128.57971,89,76,L1080600,11H20000,11H20301
|
||||
4812900000,경남 창원시 진해구,창원시 진해구,35.13306,128.71008,91,75,L1080600,11H20000,11H20301
|
||||
4817000000,경남 진주시,진주시,35.17703,128.11,81,75,L1081400,11H20000,11H20701
|
||||
4822000000,경남 통영시,통영시,34.85126,128.43528,87,68,L1082000,11H20000,11H20401
|
||||
4824000000,경남 사천시,사천시,35.00028,128.06678,80,71,L1082100,11H20000,11H20402
|
||||
4825000000,경남 김해시,김해시,35.22551,128.89167,95,77,L1080900,11H20000,11H20304
|
||||
4827000000,경남 밀양시,밀양시,35.50078,128.74894,92,83,L1081000,11H20000,11H20601
|
||||
4831000000,경남 거제시,거제시,34.87736,128.62336,90,69,L1082200,11H20000,11H20403
|
||||
4833000000,경남 양산시,양산시,35.33193,129.03941,97,79,L1080500,11H20000,11H20102
|
||||
4872000000,경남 의령군,의령군,35.31912,128.26382,83,78,L1081100,11H20000,11H20602
|
||||
4873000000,경남 함안군,함안군,35.26941,128.40871,86,77,L1081200,11H20000,11H20603
|
||||
4874000000,경남 창녕군,창녕군,35.54154,128.49453,87,83,L1081300,11H20000,11H20604
|
||||
4882000000,경남 고성군,고성군,34.9699,128.32454,85,71,L1022200,11H20000,11H20404
|
||||
4884000000,경남 남해군,남해군,34.83456,127.89447,77,68,L1082400,11H20000,11H20405
|
||||
4885000000,경남 하동군,하동군,35.0642,127.75343,74,73,L1083000,11H20000,11H20704
|
||||
4886000000,경남 산청군,산청군,35.41249,127.87562,76,80,L1083100,11H20000,11H20703
|
||||
4887000000,경남 함양군,함양군,35.51747,127.72742,74,82,L1083200,11H20000,11H20501
|
||||
4888000000,경남 거창군,거창군,35.68362,127.91166,77,86,L1083300,11H20000,11H20502
|
||||
4889000000,경남 합천군,합천군,35.56362,128.16793,81,84,L1083400,11H20000,11H20503
|
||||
5011000000,제주 제주시,제주시,33.49631,126.53321,53,38,L1091300,11G00000,11G00201
|
||||
5013000000,제주 서귀포시,서귀포시,33.25406,126.55955,53,33,L1091400,11G00000,11G00401
|
||||
5111000000,강원 춘천시,춘천시,37.87854,127.73231,73,134,L1021600,11D10000,11D10301
|
||||
5113000000,강원 원주시,원주시,37.33908,127.92206,76,122,L1021200,11D10000,11D10401
|
||||
5115000000,강원 강릉시,강릉시,37.74914,128.8785,92,131,L1022500,11D20000,11D20501
|
||||
5117000000,강원 동해시,동해시,37.52193,129.11663,97,127,L1021900,11D20000,11D20601
|
||||
5119000000,강원 태백시,태백시,37.16123,128.988,95,119,L1020300,11D20000,11D20301
|
||||
5121000000,강원 속초시,속초시,38.20428,128.59417,87,141,L1022100,11D20000,11D20401
|
||||
5123000000,강원 삼척시,삼척시,37.44709,129.16749,98,125,L1022000,11D20000,11D20602
|
||||
5172000000,강원 홍천군,홍천군,37.69442,127.89084,75,130,L1022700,11D10000,11D10302
|
||||
5173000000,강원 횡성군,횡성군,37.48896,127.98722,77,125,L1021100,11D10000,11D10402
|
||||
5175000000,강원 영월군,영월군,37.18086,128.46402,86,119,L1020800,11D10000,11D10501
|
||||
5176000000,강원 평창군,평창군,37.36792,128.39235,84,123,L1022400,11D10000,11D10503
|
||||
5177000000,강원 정선군,정선군,37.37781,128.66309,89,123,L1022600,11D10000,11D10502
|
||||
5178000000,강원 철원군,철원군,38.14406,127.31573,65,139,L1021300,11D10000,11D10101
|
||||
5179000000,강원 화천군,화천군,38.10341,127.71036,72,139,L1021400,11D10000,11D10102
|
||||
5180000000,강원 양구군,양구군,38.10729,127.99224,77,139,L1022800,11D10000,11D10202
|
||||
5181000000,강원 인제군,인제군,38.06697,128.1727,80,138,L1022900,11D10000,11D10201
|
||||
5182000000,강원 고성군,고성군,38.37796,128.47016,85,145,L1022200,11D20000,11H20404
|
||||
5183000000,강원 양양군,양양군,38.07283,128.62136,88,138,L1022300,11D20000,11D20403
|
||||
5211100000,전북 전주시 완산구,전주시 완산구,35.80919,127.12192,63,89,L1061300,11F10000,11F10201
|
||||
5211300000,전북 전주시 덕진구,전주시 덕진구,35.82639,127.13642,63,89,L1061300,11F10000,11F10201
|
||||
5213000000,전북 군산시,군산시,35.96464,126.73884,56,92,L1061600,11F10000,21F10501
|
||||
5214000000,전북 익산시,익산시,35.94527,126.95985,60,91,L1061100,11F10000,11F10202
|
||||
5218000000,전북 정읍시,정읍시,35.56687,126.85811,58,83,L1061200,11F10000,11F10203
|
||||
5219000000,전북 남원시,남원시,35.41326,127.3925,68,80,L1061400,11F10000,11F10401
|
||||
5221000000,전북 김제시,김제시,35.80057,126.88275,59,88,L1060400,11F10000,21F10502
|
||||
5271000000,전북 완주군,완주군,35.84297,127.1496,63,89,L1060500,11F10000,11F10204
|
||||
5272000000,전북 진안군,진안군,35.78872,127.42697,68,88,L1060600,11F10000,11F10303
|
||||
5273000000,전북 무주군,무주군,36.00383,127.66287,72,93,L1060700,11F10000,11F10302
|
||||
5274000000,전북 장수군,장수군,35.6443,127.5233,70,85,L1060800,11F10000,11F10301
|
||||
5275000000,전북 임실군,임실군,35.60806,127.28475,66,84,L1060900,11F10000,11F10402
|
||||
5277000000,전북 순창군,순창군,35.37139,127.13963,63,79,L1061000,11F10000,11F10403
|
||||
5279000000,전북 고창군,고창군,35.43274,126.70411,56,80,L1060100,11F10000,21F10601
|
||||
5280000000,전북 부안군,부안군,35.72853,126.73568,56,87,L1061500,11F10000,21F10602
|
||||
|
@@ -0,0 +1,12 @@
|
||||
[
|
||||
{
|
||||
"year": 2026,
|
||||
"week": 40,
|
||||
"headline": "가을이 깊어져요",
|
||||
"poem_lines": [
|
||||
"계절이 지나가는 하늘에는",
|
||||
"가을로 가득 차 있습니다."
|
||||
],
|
||||
"author": "윤동주, 「별 헤는 밤」"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,4 @@
|
||||
region_name,name,description,lat,lon,sort_order
|
||||
서울 마포구,망원한강공원,강 건너 서쪽이 넓게 트임 · 자전거 7분,37.55550,126.89500,1
|
||||
서울 마포구,하늘공원,억새 사이로 보는 노을 · 계단 있음,37.56830,126.88540,2
|
||||
서울 마포구,선유도공원,다리 위에서 강물까지 붉어요,37.54340,126.89960,3
|
||||
|
Whitespace-only changes.
@@ -0,0 +1,73 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import AirQuality, Region
|
||||
from common.enums import AirGrade, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import haversine_km
|
||||
from crud.air_crud import AirCRUD
|
||||
from services.external.airkorea import fetch_realtime, fetch_stations, parse_realtime, parse_stations
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
|
||||
_AIR_DELAY = timedelta(minutes=20)
|
||||
_RETRY_SEC = 600
|
||||
_NEAREST = 5
|
||||
GRADE_LABEL = {AirGrade.GOOD: "좋음", AirGrade.NORMAL: "보통", AirGrade.BAD: "나쁨", AirGrade.VERY_BAD: "매우나쁨"}
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
class AirService:
|
||||
def __init__(self, crud: AirCRUD = Depends(AirCRUD)) -> None:
|
||||
self.crud = crud
|
||||
|
||||
async def ensure(self, now: datetime) -> None:
|
||||
"""이번 시각(매시 20분 이후) 측정값이 없으면 전국을 다시 받는다. 갱신이 늦으면 10분 동안은 다시 부르지 않는다."""
|
||||
expected = (now - _AIR_DELAY).replace(minute=0, second=0, microsecond=0)
|
||||
err, latest = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_measured(s))
|
||||
if err is not ErrorType.SUCCESS or (latest is not None and latest >= expected):
|
||||
return
|
||||
try:
|
||||
if not await REDIS.conn.set("air:tried", "1", nx=True, ex=_RETRY_SEC):
|
||||
return
|
||||
except RedisError as e:
|
||||
LOG.error(f"[air] marker: {e}")
|
||||
if latest is None:
|
||||
await self.refresh(with_stations=True)
|
||||
return
|
||||
task = asyncio.create_task(self.refresh(with_stations=False))
|
||||
_background.add(task)
|
||||
task.add_done_callback(_background.discard)
|
||||
|
||||
async def refresh(self, with_stations: bool) -> None:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
stations = parse_stations(await fetch_stations(client)) if with_stations else []
|
||||
quality = parse_realtime(await fetch_realtime(client))
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
||||
LOG.error(f"[air] refresh: {e}")
|
||||
return
|
||||
fns = [lambda s: self.crud.upsert_quality(s, quality)]
|
||||
if stations:
|
||||
fns.insert(0, lambda s: self.crud.replace_stations(s, stations))
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(fns)
|
||||
LOG.info(f"[air] stations {len(stations)} quality {len(quality)}: {err.name}")
|
||||
|
||||
async def nearest(self, region: Region) -> Optional[AirQuality]:
|
||||
"""구 중심에서 가까운 측정소 5곳 중 초미세먼지 값이 있는 가장 가까운 곳."""
|
||||
err, stations = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.stations(s))
|
||||
if err is not ErrorType.SUCCESS or not stations:
|
||||
return None
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = sorted(stations, key=lambda st: haversine_km(lat, lon, float(st.lat), float(st.lon)))[:_NEAREST]
|
||||
err, qualities = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.qualities(s, [st.station_name for st in near]))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return None
|
||||
by_name = {q.station_name: q for q in qualities}
|
||||
return next((by_name[st.station_name] for st in near if st.station_name in by_name and by_name[st.station_name].pm25 is not None), None)
|
||||
@@ -0,0 +1,54 @@
|
||||
import re
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.auth import decode, hash_password, issue_tokens, verify_password
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
from crud.user_crud import UserCRUD
|
||||
|
||||
LOGIN_ID = re.compile(r"^[a-z0-9_]{4,20}$")
|
||||
PASSWORD_MIN = 8
|
||||
NICKNAME = re.compile(r"^\S.{0,10}\S$")
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
|
||||
self.crud = crud
|
||||
|
||||
async def signup(self, login_id: str, password: str, nickname: str) -> tuple[ErrorType, Optional[User]]:
|
||||
if not LOGIN_ID.match(login_id) or len(password) < PASSWORD_MIN or not NICKNAME.match(nickname):
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if exists is not None:
|
||||
return ErrorType.AUTH_DUPLICATE_ID, None
|
||||
hashed = await hash_password(password)
|
||||
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create(s, login_id, hashed, nickname))
|
||||
return (err, user) if err is ErrorType.SUCCESS else (ErrorType.AUTH_DUPLICATE_ID, None)
|
||||
|
||||
async def login(self, login_id: str, password: str) -> tuple[ErrorType, Optional[User]]:
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if user is None or user.password is None or user.status != 1 or not await verify_password(password, user.password):
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
|
||||
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
|
||||
if claims is None:
|
||||
return ErrorType.AUTH_TOKEN_INVALID, None
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, uuid.UUID(claims["sub"])))
|
||||
if err is not ErrorType.SUCCESS or user is None or user.status != 1 or user.token_version != claims.get("ver"):
|
||||
return ErrorType.AUTH_TOKEN_INVALID, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
@staticmethod
|
||||
def tokens(user: User) -> tuple[str, str]:
|
||||
return issue_tokens(user)
|
||||
Whitespace-only changes.
@@ -0,0 +1,196 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from statistics import mean
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.text import hour_label
|
||||
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
|
||||
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_UNKNOWN = 70
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Hour:
|
||||
hour: int
|
||||
feels_c: float
|
||||
rain_type: RainType
|
||||
rain_prob: int
|
||||
wind_ms: Optional[float]
|
||||
humidity: int
|
||||
sky: Sky
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Context:
|
||||
day: date
|
||||
is_holiday: bool
|
||||
pm25: Optional[int]
|
||||
air_label: Optional[str]
|
||||
moon: float
|
||||
sunset_score: Optional[int]
|
||||
wind_warning: bool
|
||||
lookahead_rain_prob: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Result:
|
||||
score: int
|
||||
factors: dict[str, int]
|
||||
notes: dict[str, str]
|
||||
zero_reason: Optional[str]
|
||||
summary: str
|
||||
window: tuple[int, int] = field(default=(0, 0))
|
||||
|
||||
|
||||
def _clamp(v: float) -> int:
|
||||
return round(max(0.0, min(100.0, v)))
|
||||
|
||||
|
||||
def _linear(v: float, zero: float, full: float) -> int:
|
||||
return _clamp((v - zero) / (full - zero) * 100)
|
||||
|
||||
|
||||
def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
t = feels + rule.get("offset", 0)
|
||||
shown = f"정상 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||
return _clamp(100 - 8 * dist), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if dist == 0 else '밖'}"
|
||||
return _linear(t, rule["zero"], rule["full"]), shown
|
||||
|
||||
|
||||
def rain_score(rule: dict, max_prob: int, raining: bool) -> tuple[int, str]:
|
||||
if rule["dir"] == "wet":
|
||||
return (100 if raining else _clamp(max_prob)), (f"비 소식, 확률 {max_prob}%" if raining else f"비 확률 {max_prob}%, 비 오면 올라가요")
|
||||
return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, 확률 {max_prob}%" if raining else f"비 확률 {max_prob}%")
|
||||
|
||||
|
||||
def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
|
||||
if wind is None or rule["type"] == "ignore":
|
||||
return (_UNKNOWN if wind is None else 50), ("바람 정보 없음" if wind is None else f"바람 초속 {wind:g}m")
|
||||
note = f"바람 초속 {wind:g}m"
|
||||
if rule["type"] == "calm":
|
||||
return (100 if wind <= rule["ok"] else _linear(wind, rule["limit"], rule["ok"])), note
|
||||
if rule["type"] == "moderate":
|
||||
if 2 <= wind <= 5:
|
||||
return 100, note
|
||||
return (_clamp(60 + 20 * wind) if wind < 2 else _linear(wind, 12, 5)), note
|
||||
return _linear(wind, 0, 8), note
|
||||
|
||||
|
||||
def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
note = f"습도 {round(humidity)}%"
|
||||
if rule["type"] == "range":
|
||||
dist = 0 if rule["lo"] <= humidity <= rule["hi"] else min(abs(humidity - rule["lo"]), abs(humidity - rule["hi"]))
|
||||
return _clamp(100 - 2 * dist), note
|
||||
if rule["type"] == "higher":
|
||||
return _linear(humidity, 40, 90), note
|
||||
if rule["type"] == "lower":
|
||||
return _linear(humidity, 90, 40), note
|
||||
return 50, note
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
if pm25 is None:
|
||||
return _UNKNOWN, "미세먼지 정보 없음"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
kind = rule["type"]
|
||||
if kind == "weekday":
|
||||
key = "holiday" if ctx.is_holiday and "holiday" in rule else _WEEKDAY[ctx.day.weekday()]
|
||||
v = rule.get(key, rule.get("default", 100))
|
||||
return _clamp(v), f"{_WEEKDAY_KO[ctx.day.weekday()]}요일{' 공휴일' if ctx.is_holiday else ''}"
|
||||
if kind == "moon":
|
||||
return _clamp(20 + 80 * (1 - ctx.moon)), f"달 밝기 {round(ctx.moon * 100)}%"
|
||||
if kind == "sunset_score":
|
||||
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else "노을 점수 계산 전"
|
||||
)
|
||||
return _clamp(rule["value"]), "시간대 그대로"
|
||||
|
||||
|
||||
def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
"""걸린 조건의 이유와 상한(cap). cap 이 없으면 0점. (최소, 최대) 값은 '이상'이면 최대, '미만'이면 최소로 본다."""
|
||||
for r in rules:
|
||||
v = agg.get(r["field"])
|
||||
if isinstance(v, tuple):
|
||||
v = v[1] if r["op"] == ">=" else v[0]
|
||||
if v is None:
|
||||
continue
|
||||
hit = (v >= r["value"]) if r["op"] == ">=" else (v < r["value"]) if r["op"] == "<" else (v == r["value"])
|
||||
if hit:
|
||||
return zero_text(r), r.get("cap", 0)
|
||||
return None, None
|
||||
|
||||
|
||||
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%"}
|
||||
|
||||
|
||||
def zero_text(r: dict) -> str:
|
||||
if r["field"] == "warning":
|
||||
return "강풍 특보가 있으면"
|
||||
op = "이상" if r["op"] == ">=" else "미만"
|
||||
return f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {op}이면"
|
||||
|
||||
|
||||
def zero_rules_text(rules: list[dict]) -> str:
|
||||
if not rules:
|
||||
return "없음 (재미로 보는 지수)"
|
||||
parts = [zero_text(r) for r in rules]
|
||||
caps = {r.get("cap") for r in rules}
|
||||
tail = f"{caps.pop()}점 아래로" if caps != {None} and len(caps) == 1 else "바로 0점"
|
||||
return " 또는 ".join(p.removesuffix("이면") for p in parts) + f"이면 {tail}"
|
||||
|
||||
|
||||
def _summary(hours: list[Hour]) -> str:
|
||||
mid = hours[len(hours) // 2]
|
||||
wind = mid.wind_ms
|
||||
tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else (
|
||||
"바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else "맑음"
|
||||
)
|
||||
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
|
||||
|
||||
|
||||
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
|
||||
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
for hours in windows:
|
||||
if not hours:
|
||||
continue
|
||||
max_prob = max(max(h.rain_prob for h in hours), ctx.lookahead_rain_prob)
|
||||
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
||||
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
||||
feels = mean(h.feels_c for h in hours)
|
||||
scored = {
|
||||
"temp": temp_score(rules["temp"], feels),
|
||||
"rain": rain_score(rules["rain"], max_prob, raining),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = round(sum(factors[a] * weights[a] for a in AXES) / 100)
|
||||
agg = {
|
||||
"rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25,
|
||||
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
score = min(score, cap)
|
||||
result = Result(score=score, factors=factors, notes=notes, zero_reason=reason, summary=_summary(hours), window=(hours[0].hour, hours[-1].hour))
|
||||
if best is None or result.score > best.score:
|
||||
best = result
|
||||
return best
|
||||
@@ -0,0 +1,11 @@
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_SYNODIC_DAYS = 29.530588
|
||||
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def illumination(at: datetime) -> float:
|
||||
"""달이 밝게 보이는 비율 0(그믐)~1(보름). 평균 삭망월 근사."""
|
||||
phase = ((at - _KNOWN_NEW_MOON).total_seconds() / 86400 % _SYNODIC_DAYS) / _SYNODIC_DAYS
|
||||
return (1 - math.cos(2 * math.pi * phase)) / 2
|
||||
@@ -0,0 +1,61 @@
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
|
||||
DISTANCES_KM = (20, 50, 100)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Layers:
|
||||
low: float
|
||||
mid: float
|
||||
high: float
|
||||
|
||||
|
||||
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
|
||||
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
|
||||
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
|
||||
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
|
||||
def grade(value: int) -> SkyGrade:
|
||||
if value >= 80:
|
||||
return SkyGrade.RED
|
||||
if value >= 60:
|
||||
return SkyGrade.GLOW
|
||||
if value >= 40:
|
||||
return SkyGrade.SOFT
|
||||
return SkyGrade.GRAY
|
||||
|
||||
|
||||
def confidence(model_scores: list[int]) -> Confidence:
|
||||
"""모델끼리 점수가 비슷할수록 확신이 높다."""
|
||||
if len(model_scores) < 2:
|
||||
return Confidence.LOW
|
||||
spread = statistics.pstdev(model_scores)
|
||||
return Confidence.HIGH if spread < 8 else Confidence.NORMAL if spread < 15 else Confidence.LOW
|
||||
|
||||
|
||||
def best_times(kind: SkyType, sun_at: datetime, twilight_at: datetime, high_cloud: float) -> list[dict]:
|
||||
"""노을은 해 진 뒤 10~20분이 가장 붉다. 높은 구름이 많을수록 늦게까지 물든다."""
|
||||
peak_min = 10 + round(min(high_cloud, 100) / 10)
|
||||
sun_at, twilight_at = sun_at.replace(second=0, microsecond=0), twilight_at.replace(second=0, microsecond=0)
|
||||
if kind is SkyType.SUNSET:
|
||||
return [
|
||||
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 져요"},
|
||||
{"at": (sun_at + timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "보랏빛 하늘"},
|
||||
]
|
||||
return [
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "푸른 새벽"},
|
||||
{"at": (sun_at - timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
|
||||
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 떠요"},
|
||||
]
|
||||
|
||||
|
||||
GRADE_LABEL = {SkyGrade.RED: "붉음", SkyGrade.GLOW: "고움", SkyGrade.SOFT: "은은함", SkyGrade.GRAY: "흐림"}
|
||||
@@ -0,0 +1,53 @@
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
_SUN_ALTITUDE = -0.833
|
||||
_CIVIL_ALTITUDE = -6.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SunTimes:
|
||||
sunrise_at: datetime
|
||||
sunset_at: datetime
|
||||
dusk_end_at: datetime
|
||||
sunset_azimuth: int
|
||||
dawn_start_at: datetime
|
||||
sunrise_azimuth: int
|
||||
|
||||
|
||||
def _solar(d: date, lon: float) -> tuple[float, float]:
|
||||
"""NOAA 근사식. (태양 적위 도, 남중 시각 UTC 분)."""
|
||||
g = 2 * math.pi / 365 * (d.timetuple().tm_yday - 1)
|
||||
eqtime = 229.18 * (
|
||||
0.000075 + 0.001868 * math.cos(g) - 0.032077 * math.sin(g) - 0.014615 * math.cos(2 * g) - 0.040849 * math.sin(2 * g)
|
||||
)
|
||||
decl = (
|
||||
0.006918 - 0.399912 * math.cos(g) + 0.070257 * math.sin(g) - 0.006758 * math.cos(2 * g)
|
||||
+ 0.000907 * math.sin(2 * g) - 0.002697 * math.cos(3 * g) + 0.00148 * math.sin(3 * g)
|
||||
)
|
||||
return math.degrees(decl), 720 - 4 * lon - eqtime
|
||||
|
||||
|
||||
def _hour_angle(lat: float, decl: float, altitude: float) -> float:
|
||||
phi, dl = math.radians(lat), math.radians(decl)
|
||||
cos_h = (math.sin(math.radians(altitude)) - math.sin(phi) * math.sin(dl)) / (math.cos(phi) * math.cos(dl))
|
||||
return math.degrees(math.acos(max(-1.0, min(1.0, cos_h))))
|
||||
|
||||
|
||||
def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
decl, noon_min = _solar(d, lon)
|
||||
base = datetime(d.year, d.month, d.day, tzinfo=timezone.utc)
|
||||
at = lambda minutes: base + timedelta(minutes=minutes) # noqa: E731
|
||||
h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4
|
||||
h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4
|
||||
phi, dl = math.radians(lat), math.radians(decl)
|
||||
azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi)))))
|
||||
return SunTimes(
|
||||
sunrise_at=at(noon_min - h_sun),
|
||||
sunset_at=at(noon_min + h_sun),
|
||||
dusk_end_at=at(noon_min + h_civil),
|
||||
sunset_azimuth=round(360 - azimuth),
|
||||
dawn_start_at=at(noon_min - h_civil),
|
||||
sunrise_azimuth=round(azimuth),
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def wet_bulb_c(temp_c: float, humidity: float) -> float:
|
||||
"""Stull(2011) 습구온도 근사식."""
|
||||
t, rh = temp_c, humidity
|
||||
return (
|
||||
t * math.atan(0.151977 * math.sqrt(rh + 8.313659))
|
||||
+ math.atan(t + rh)
|
||||
- math.atan(rh - 1.676331)
|
||||
+ 0.00391838 * rh ** 1.5 * math.atan(0.023101 * rh)
|
||||
- 4.686035
|
||||
)
|
||||
|
||||
|
||||
def feels_like_c(temp_c: float, humidity: float, wind_ms: Optional[float], month: int) -> float:
|
||||
"""기상청 체감온도: 5~9월은 여름식(습도), 10~4월은 겨울식(바람)."""
|
||||
if 5 <= month <= 9:
|
||||
tw = wet_bulb_c(temp_c, humidity)
|
||||
return round(-0.2442 + 0.55399 * tw + 0.45535 * temp_c - 0.0022 * tw ** 2 + 0.00278 * tw * temp_c + 3.0, 1)
|
||||
v = (wind_ms or 0.0) * 3.6
|
||||
if temp_c > 10 or v < 4.8:
|
||||
return round(temp_c, 1)
|
||||
return round(13.12 + 0.6215 * temp_c - 11.37 * v ** 0.16 + 0.3965 * temp_c * v ** 0.16, 1)
|
||||
|
||||
|
||||
def discomfort_index(temp_c: float, humidity: float) -> int:
|
||||
return round(0.81 * temp_c + 0.01 * humidity * (0.99 * temp_c - 14.3) + 46.3)
|
||||
Whitespace-only changes.
+56
@@ -0,0 +1,56 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
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"
|
||||
|
||||
|
||||
def _int(v) -> Optional[int]:
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _measured_at(text: str) -> datetime:
|
||||
""""2026-10-02 08:00" (KST). 자정은 "24:00" 으로 온다."""
|
||||
day, hm = text.split()
|
||||
if hm == "24:00":
|
||||
return datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=KST) + timedelta(days=1)
|
||||
return datetime.strptime(text, "%Y-%m-%d %H:%M").replace(tzinfo=KST)
|
||||
|
||||
|
||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"})
|
||||
|
||||
|
||||
async def fetch_stations(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"})
|
||||
|
||||
|
||||
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||
rows = []
|
||||
for it in items:
|
||||
if not it.get("stationName") or not it.get("dataTime"):
|
||||
continue
|
||||
grades = [g for g in (_int(it.get("pm25Grade")), _int(it.get("pm10Grade"))) if g]
|
||||
rows.append({
|
||||
"station_name": it["stationName"], "pm25": _int(it.get("pm25Value")), "pm10": _int(it.get("pm10Value")),
|
||||
"grade": max(grades) if grades else None, "measured_at": _measured_at(it["dataTime"]),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def parse_stations(items: list[dict]) -> list[dict]:
|
||||
rows = []
|
||||
for it in items:
|
||||
try:
|
||||
rows.append({"station_name": it["stationName"], "lat": float(it["dmX"]), "lon": float(it["dmY"])})
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
return rows
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user