"""和风天气聚合:服务端持有 Key/Host,设备只拿精简结果。 配置优先级:平台设置(库)> .env;配置直读库不缓存,只有查询结果进 Redis。 缓存键 ``weather:{city}``,TTL 30 分钟(01-总体设计.md 3.4)。 """ from __future__ import annotations from typing import Any import httpx from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import settings from app.models import PlatformSetting from app.services import redis_store class WeatherNotConfigured(RuntimeError): """缺 API Host:和风新账号必须用专属域名,否则一律 403 Invalid Host。""" class WeatherUpstreamError(RuntimeError): pass async def _platform_value(db: AsyncSession, key: str) -> str | None: """平台配置直读库,不走 Redis。 配置是运维级的低频写入,读一次主键查询成本可忽略;一旦进缓存,一条写错的 值(如文档示例 Host ``abc1234xyz.re.qweatherapi.com``)会压住库和 .env, 只能手动清 Redis 才能恢复——这类故障不值得为省一次查询去承担。 """ row = await db.get(PlatformSetting, key) return str(row.value) if row and row.value else None async def _conf(db: AsyncSession) -> tuple[str, str]: key = await _platform_value(db, "qweather.key") or settings.qweather_key host = await _platform_value(db, "qweather.host") or settings.qweather_host if not key or not host: raise WeatherNotConfigured( "和风天气未配置:登录和风控制台 → 设置,复制账号专属 API Host" "(形如 abc1234xyz.re.qweatherapi.com)填入 QWEATHER_HOST 或管理端设置" ) h = host.strip().rstrip("/") if not h.startswith(("http://", "https://")): h = "https://" + h return key, h async def _get(http: httpx.AsyncClient, url: str, params: dict[str, Any], key: str = "") -> dict[str, Any]: # 和风新版:API Key 走 X-QW-Api-Key 头;JWT 走 Authorization: Bearer。 # 早期文档里的 ?key= 查询参数对新建项目已不再生效(会返回 401),这里不再用。 headers: dict[str, str] = {} if key: if key.count(".") == 2 and len(key) > 80: # JWT:xxx.yyy.zzz headers["Authorization"] = f"Bearer {key}" else: headers["X-QW-Api-Key"] = key resp = await http.get(url, params=params, headers=headers) if resp.status_code >= 400: raise WeatherUpstreamError(f"和风返回 HTTP {resp.status_code}") data = resp.json() # 新版错误体是 {"error": {"status": 403, "title": ...}} if isinstance(data, dict) and "error" in data: err = data["error"] raise WeatherUpstreamError( f"和风错误 {err.get('status')}: {err.get('title', '')} {err.get('detail', '')}".strip() ) return data async def _location_id(http: httpx.AsyncClient, host: str, key: str, city: str) -> tuple[str, str]: """城市名 → LocationID。返回 (id, 规范名)。""" data = await _get(http, f"{host}/geo/v2/city/lookup", {"location": city, "number": 1, "lang": "zh"}, key) items = data.get("location") or [] if not items: raise WeatherUpstreamError(f"找不到城市:{city}") return items[0]["id"], items[0]["name"] def _slim(city: str, loc_id: str, now: dict[str, Any], hourly: list[dict[str, Any]]) -> dict[str, Any]: """设备端要的字段越少越好:360×360 屏只放得下这些。""" return { "ok": True, "city": city, "location_id": loc_id, "temp": int(now.get("temp", 0)), "feels": int(now.get("feelsLike", 0)), "text": now.get("text", ""), "code": now.get("icon", ""), # 和风图标码,固件据此画天气图标 "humidity": int(now.get("humidity", 0)), "wind_dir": now.get("windDir", ""), "wind_scale": now.get("windScale", ""), "obs_time": now.get("obsTime", ""), "hourly": [ {"time": h.get("fxTime", "")[11:16], "temp": int(h.get("temp", 0)), "text": h.get("text", ""), "code": h.get("icon", ""), "pop": int(h.get("pop", 0) or 0)} for h in hourly[:3] ], "source": "qweather", } async def is_configured(db: AsyncSession) -> bool: """有效配置(管理端设置优先)是否齐备,供 /healthz 使用。""" try: await _conf(db) return True except WeatherNotConfigured: return False async def now(db: AsyncSession, city: str) -> dict[str, Any]: cached = await redis_store.get_weather(city) if cached: cached["cached"] = True return cached key, host = await _conf(db) timeout = httpx.Timeout(8.0, connect=5.0) try: async with httpx.AsyncClient(timeout=timeout, headers={"Accept-Encoding": "gzip"}) as http: loc_id, name = await _location_id(http, host, key, city) current = await _get(http, f"{host}/v7/weather/now", {"location": loc_id, "lang": "zh"}, key) try: f24 = await _get(http, f"{host}/v7/weather/24h", {"location": loc_id, "lang": "zh"}, key) hourly = f24.get("hourly") or [] except WeatherUpstreamError: hourly = [] # 24h 可能是付费套餐,缺了不影响当前天气 except httpx.HTTPError as exc: # DNS/连接/超时都归到上游不可用,让设备拿到 502 而不是 500 raise WeatherUpstreamError(f"和风请求失败:{exc.__class__.__name__}") from exc payload = _slim(name or city, loc_id, current.get("now") or {}, hourly) await redis_store.set_weather(city, payload) return payload