feat: 지역 검색 페이지에 오늘 날씨·각을 서버가 채워 준다 (nginx → /v1/seo/today, 실패하면 정적 HTML)
This commit is contained in:
1 parent
2ca060b626
commit
a68268234d
8 files changed
+183
-1
No files matched your search
@@ -31,6 +31,9 @@ class Settings(BaseSettings):
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
|
||||
frontend_internal_url: str = "http://frontend"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
jwt_access_minutes: int = 60
|
||||
|
||||
@@ -14,6 +14,7 @@ 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.seo.seo import router as seo_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
from router.v1.weather.weather import router as weather_router
|
||||
@@ -43,6 +44,7 @@ app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,17 @@
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from common.enums import ErrorType
|
||||
from services.seo_service import SeoService
|
||||
|
||||
router = APIRouter(prefix="/v1/seo", tags=["seo"])
|
||||
|
||||
_SLUG = r"^[a-z]+$"
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}", response_class=HTMLResponse, summary="지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)")
|
||||
async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"today/{sido}/{place}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
@@ -0,0 +1,84 @@
|
||||
import re
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends
|
||||
|
||||
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 KST, now_kst
|
||||
from config.settings import settings
|
||||
from crud.region_crud import RegionCRUD
|
||||
from router.v1.feed.protocol import Res_Feed
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.sun import sun_times
|
||||
from services.feed_service import FeedService
|
||||
|
||||
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>오늘 (.+?) 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
|
||||
|
||||
def _clock(at: datetime) -> str:
|
||||
at = at.astimezone(KST)
|
||||
h = at.hour % 12 or 12
|
||||
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
|
||||
|
||||
|
||||
def today_line(feed: Res_Feed, sunset_at: Optional[datetime]) -> str:
|
||||
"""검색 결과 요약에 보일 오늘 한 줄: 지금 기온·상태, 구간별 1위 각, 해 지는 시각."""
|
||||
parts = []
|
||||
h = feed.hero
|
||||
if h and h.temp_c is not None:
|
||||
status = "·".join(f"{s.label} {s.value}" for s in h.status)
|
||||
parts.append(f"지금 {round(h.temp_c)}°" + (f", {status}" if status else "") + ".")
|
||||
firsts = [f"{label}은 {s.name}" for slot, label in SLOT_LABEL.items() for s in feed.stories if s.slot_ranks.get(slot) == 1]
|
||||
if firsts:
|
||||
parts.append(", ".join(firsts) + ".")
|
||||
if sunset_at:
|
||||
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
line = today_line(feed, sunset_at)
|
||||
if not line:
|
||||
return template
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
|
||||
|
||||
|
||||
class SeoService:
|
||||
def __init__(self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD)) -> None:
|
||||
self.feed, self.regions = feed, regions
|
||||
|
||||
async def template(self, path: str) -> Optional[str]:
|
||||
"""프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html)."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
r = await client.get(f"{settings.frontend_internal_url}/{path}.html")
|
||||
except httpx.HTTPError as e:
|
||||
LOG.error(f"[seo] template {path}: {e}")
|
||||
return None
|
||||
return r.text if r.status_code == 200 and _CODE.search(r.text) else None
|
||||
|
||||
async def page(self, path: str) -> tuple[ErrorType, Optional[str]]:
|
||||
template = await self.template(path)
|
||||
if template is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
code = _CODE.search(template).group(1)
|
||||
err, feed = await self.feed.feed(code)
|
||||
if err is not ErrorType.SUCCESS or feed is None:
|
||||
LOG.error(f"[seo] feed {code}: {err}")
|
||||
return ErrorType.SUCCESS, template
|
||||
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
|
||||
sunset_at = sun_times(now_kst().date(), float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
@@ -0,0 +1,56 @@
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, fill, today_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
|
||||
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>오늘 서울 중구 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
|
||||
)
|
||||
|
||||
|
||||
def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex:
|
||||
return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks)
|
||||
|
||||
|
||||
def _feed() -> Res_Feed:
|
||||
stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})]
|
||||
hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4,
|
||||
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")])
|
||||
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
|
||||
|
||||
|
||||
def test_today_line_has_temp_status_slot_firsts_and_sunset():
|
||||
line = today_line(_feed(), datetime(2026, 10, 14, 17, 52, tzinfo=KST))
|
||||
assert line == "지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
|
||||
|
||||
|
||||
def test_fill_puts_today_into_description_and_body():
|
||||
html = fill(TEMPLATE, _feed(), "서울 중구", None)
|
||||
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
|
||||
assert "<h1>오늘 서울 중구 날씨, 뭐 할까?</h1><p>지금 13°" in html
|
||||
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
|
||||
|
||||
|
||||
def test_fill_keeps_template_when_no_weather():
|
||||
assert fill(TEMPLATE, Res_Feed(), "서울 중구", None) == TEMPLATE
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/seoul/jung" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/seoul/jung")
|
||||
missing = await client.get("/v1/seo/today/seoul/nowhere")
|
||||
assert page.status_code == 200 and "<h1>오늘 서울 중구 날씨, 뭐 할까?</h1><p>지금 20°" in page.text
|
||||
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
|
||||
assert missing.status_code == 404
|
||||
@@ -31,6 +31,23 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
|
||||
location ~ ^/today/[a-z]+/[a-z]+$ {
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://backend:9800;
|
||||
proxy_pass $api/v1/seo$uri;
|
||||
proxy_set_header Host $host;
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_read_timeout 20s;
|
||||
proxy_intercept_errors on;
|
||||
error_page 404 500 502 503 504 = @static;
|
||||
}
|
||||
|
||||
location @static {
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri.html /index.html;
|
||||
}
|
||||
|
||||
# SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403)
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
|
||||
@@ -12,7 +12,7 @@ const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</
|
||||
const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
|
||||
|
||||
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
|
||||
const PAGES: { path: string; title: string; description: string; body: string }[] = [
|
||||
const PAGES: { path: string; title: string; description: string; body: string; code?: string }[] = [
|
||||
{
|
||||
path: 'gak',
|
||||
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
|
||||
@@ -46,6 +46,7 @@ for (const r of regionPages) {
|
||||
const parts = r.regions.length > 1 ? `<p>${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.</p>` : ''
|
||||
PAGES.push({
|
||||
path: `today/${r.path}`,
|
||||
code: r.main,
|
||||
title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`,
|
||||
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
|
||||
body: `<h1>오늘 ${r.name} 날씨, 뭐 할까?</h1><p>${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
|
||||
@@ -74,6 +75,8 @@ function seoPages(): Plugin {
|
||||
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
|
||||
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
|
||||
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)
|
||||
// 서버가 오늘 날씨를 채울 때 이 페이지의 구를 알아보는 표시
|
||||
.replace('</head>', p.code ? `<meta name="region-code" content="${p.code}" />\n </head>` : '</head>')
|
||||
const file = resolve(outDir, `${p.path}.html`)
|
||||
mkdirSync(dirname(file), { recursive: true })
|
||||
writeFileSync(file, html)
|
||||
|
||||
Reference in new issue
Block a user