136 lines
4.3 KiB
Python
136 lines
4.3 KiB
Python
"""码表读取:城市(省/市/区县)与星座。
|
||
|
||
两张表都是「管理端维护、全站只读」的低频数据,读的时候走 Redis 缓存,
|
||
管理端一改就 invalidate,下次请求重建。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from typing import Any
|
||
|
||
from sqlalchemy import select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.models import Region, ZodiacSign
|
||
from app.services import redis_store
|
||
|
||
REGION_TREE_KEY = "meta:regions:tree"
|
||
ZODIAC_KEY = "meta:zodiacs"
|
||
CACHE_TTL = 3600
|
||
|
||
|
||
# ---------------- 城市 ----------------
|
||
async def get_region(db: AsyncSession, code: str | None) -> Region | None:
|
||
if not code:
|
||
return None
|
||
return await db.get(Region, code)
|
||
|
||
|
||
async def region_chain(db: AsyncSession, code: str | None) -> list[Region]:
|
||
"""自顶向下的路径:省 → 市 → 区县(走到哪层算哪层)。"""
|
||
chain: list[Region] = []
|
||
seen: set[str] = set()
|
||
cur = await get_region(db, code)
|
||
while cur is not None and cur.code not in seen:
|
||
chain.append(cur)
|
||
seen.add(cur.code)
|
||
cur = await get_region(db, cur.parent_code)
|
||
chain.reverse()
|
||
return chain
|
||
|
||
|
||
async def resolve_place(db: AsyncSession, code: str | None) -> tuple[str | None, str | None, str]:
|
||
"""返回 (城市名, 完整路径, 时区)。
|
||
|
||
城市名取路径上最靠下的「市级」节点;直辖市没有市级节点就用省名,
|
||
这样天气接口拿到的始终是一个可查询的城市名。
|
||
"""
|
||
chain = await region_chain(db, code)
|
||
if not chain:
|
||
return None, None, "Asia/Shanghai"
|
||
|
||
city = next((r.name for r in reversed(chain) if r.level == 2), None)
|
||
if city is None:
|
||
city = next((r.name for r in reversed(chain) if r.level == 1), chain[-1].name)
|
||
place = " ".join(r.name for r in chain)
|
||
tz = chain[-1].timezone or "Asia/Shanghai"
|
||
return city, place, tz
|
||
|
||
|
||
async def region_tree(db: AsyncSession) -> list[dict[str, Any]]:
|
||
cached = await redis_store.cache_get(REGION_TREE_KEY)
|
||
if cached:
|
||
return cached
|
||
|
||
rows = (
|
||
await db.execute(
|
||
select(Region).where(Region.enabled.is_(True)).order_by(Region.sort_order, Region.code)
|
||
)
|
||
).scalars().all()
|
||
|
||
nodes: dict[str, dict[str, Any]] = {
|
||
r.code: {"code": r.code, "name": r.name, "level": r.level, "children": []} for r in rows
|
||
}
|
||
roots: list[dict[str, Any]] = []
|
||
for r in rows:
|
||
node = nodes[r.code]
|
||
parent = nodes.get(r.parent_code or "")
|
||
if parent is None:
|
||
roots.append(node)
|
||
else:
|
||
parent["children"].append(node)
|
||
|
||
# 叶子节点不带空 children,前端 Cascader 才认得出「可选终点」
|
||
def trim(items: list[dict[str, Any]]) -> None:
|
||
for it in items:
|
||
if it["children"]:
|
||
trim(it["children"])
|
||
else:
|
||
it.pop("children", None)
|
||
|
||
trim(roots)
|
||
await redis_store.cache_set(REGION_TREE_KEY, roots, CACHE_TTL)
|
||
return roots
|
||
|
||
|
||
# ---------------- 星座 ----------------
|
||
async def zodiacs(db: AsyncSession, include_disabled: bool = False) -> list[dict[str, Any]]:
|
||
cached = None if include_disabled else await redis_store.cache_get(ZODIAC_KEY)
|
||
if cached:
|
||
return cached
|
||
|
||
stmt = select(ZodiacSign).order_by(ZodiacSign.sort_order)
|
||
if not include_disabled:
|
||
stmt = stmt.where(ZodiacSign.enabled.is_(True))
|
||
rows = (await db.execute(stmt)).scalars().all()
|
||
data = [
|
||
{
|
||
"code": z.code,
|
||
"name_cn": z.name_cn,
|
||
"name_en": z.name_en,
|
||
"symbol": z.symbol,
|
||
"element": z.element,
|
||
"start_month": z.start_month,
|
||
"start_day": z.start_day,
|
||
"end_month": z.end_month,
|
||
"end_day": z.end_day,
|
||
"date_range": f"{z.start_month:02d}-{z.start_day:02d} ~ {z.end_month:02d}-{z.end_day:02d}",
|
||
"intro": z.intro,
|
||
"sort_order": z.sort_order,
|
||
"enabled": z.enabled,
|
||
}
|
||
for z in rows
|
||
]
|
||
if not include_disabled:
|
||
await redis_store.cache_set(ZODIAC_KEY, data, CACHE_TTL)
|
||
return data
|
||
|
||
|
||
async def zodiac_map(db: AsyncSession) -> dict[str, dict[str, Any]]:
|
||
return {z["code"]: z for z in await zodiacs(db)}
|
||
|
||
|
||
async def invalidate() -> None:
|
||
await redis_store.cache_del(REGION_TREE_KEY, ZODIAC_KEY)
|