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
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}일"
|
||||
Reference in new issue
Block a user