天气设置
parent
81a369b845
commit
aa7cb178bb
|
|
@ -25,10 +25,7 @@ REDIS_URL=redis://127.0.0.1:6379/9
|
|||
# REDIS_URL=redis://host.docker.internal:6379/9
|
||||
|
||||
# ---- 和风天气 ----
|
||||
# Key 直接可用;Host 是账号专属的,登录控制台 → 设置 复制(形如 abc1234xyz.re.qweatherapi.com)
|
||||
# 旧的 devapi/api.qweather.com 已返回 403 Invalid Host
|
||||
QWEATHER_KEY=HE2204271924421425
|
||||
QWEATHER_HOST=
|
||||
# Key / Host 只保存在数据库,由管理端「平台设置」维护;这里不再读取。
|
||||
|
||||
# ---- 业务参数 ----
|
||||
SESSION_TTL_SECONDS=604800
|
||||
|
|
|
|||
|
|
@ -192,7 +192,7 @@ nex_buddy/
|
|||
|---|---|
|
||||
| `DATABASE_URL` | `postgresql+asyncpg://用户:口令@主机:5432/nex_buddy` |
|
||||
| `REDIS_URL` | `redis://主机:6379/9`(db 9 是项目专属库) |
|
||||
| `QWEATHER_KEY` / `QWEATHER_HOST` | 和风凭据;也可在管理端「平台设置」里改(库里优先) |
|
||||
| 和风 `API Key` / `API Host` | 只在管理端「平台设置」保存到数据库,运行时不读 `.env` |
|
||||
| `WEB_BASE_URL` | 二维码里 Web 地址的**覆盖值**;空则按设备请求 Host 推导(同域部署不用配) |
|
||||
| `DATA_DIR` | 运行时资源根目录,默认项目根 `data/`;服务器/容器部署可指向宿主机挂载点 |
|
||||
| `BACKEND_PORT` / `FRONTEND_PORT` | 端口(默认 8000 / 5173):开发时是监听端口,Docker 部署时是宿主机映射端口;容器内固定为 8000 / 80。localhost 的 CORS 源自动跟随 |
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ for arg in "$@"; do
|
|||
done
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo "!! 缺少 .env:先执行 cp .env.example .env,并填写 DATABASE_URL / REDIS_URL / QWEATHER_*" >&2
|
||||
echo "!! 缺少 .env:先执行 cp .env.example .env,并填写 DATABASE_URL / REDIS_URL" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
|
|
|||
|
|
@ -31,9 +31,7 @@ class Settings(BaseSettings):
|
|||
database_url: str = "postgresql+asyncpg://postgres:sagacity@192.168.124.203:5432/nex_buddy"
|
||||
redis_url: str = "redis://192.168.124.203:6379/9"
|
||||
|
||||
# 和风:Key 与 Host 都只在服务端;Host 是账号专属域名,缺了会 403 Invalid Host
|
||||
qweather_key: str = ""
|
||||
qweather_host: str = "p52yvqedka.re.qweatherapi.com"
|
||||
# 和风 Key / Host 只存数据库,由管理端「平台设置」维护,不从 .env 读取。
|
||||
# 可选:和风请求走指定代理(服务器本身出不了网时用,如 http://10.0.0.2:3128)。
|
||||
# 留空则跟随 HTTP(S)_PROXY / ALL_PROXY 环境变量——httpx 默认就是这种行为,
|
||||
# 而容器里继承到的失效代理正是"连不上和风"最常见的原因之一。
|
||||
|
|
@ -91,17 +89,6 @@ class Settings(BaseSettings):
|
|||
|
||||
return out
|
||||
|
||||
@property
|
||||
def qweather_host_url(self) -> str:
|
||||
"""归一化成 https://host,接受带协议/带斜杠的写法。"""
|
||||
h = (self.qweather_host or "").strip().rstrip("/")
|
||||
if not h:
|
||||
return ""
|
||||
if not h.startswith(("http://", "https://")):
|
||||
h = "https://" + h
|
||||
return h
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
"""平台运行时设置(和风 Key/Host 等):存库 + Redis 缓存,.env 兜底。"""
|
||||
"""平台运行时设置(和风 Key/Host 等):只存数据库,运行时直读。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"""和风天气聚合:服务端持有 Key/Host,设备只拿精简结果。
|
||||
|
||||
配置优先级:平台设置(库)> .env;配置直读库不缓存,只有查询结果进 Redis。
|
||||
配置只读平台设置(库),不读 .env;配置直读库不缓存,只有查询结果进 Redis。
|
||||
缓存键 ``weather:{city}``,TTL 30 分钟(01-总体设计.md 3.4)。
|
||||
"""
|
||||
|
||||
|
|
@ -32,8 +32,25 @@ class WeatherUpstreamError(RuntimeError):
|
|||
pass
|
||||
|
||||
|
||||
def _upstream_msg(data: Any) -> str:
|
||||
"""取上游响应里的消息字段,不做二次拼接。"""
|
||||
if not isinstance(data, dict):
|
||||
return ""
|
||||
err = data.get("error")
|
||||
if isinstance(err, dict):
|
||||
for key in ("detail", "title", "msg", "message"):
|
||||
value = str(err.get(key) or "").strip()
|
||||
if value:
|
||||
return value
|
||||
for key in ("msg", "message", "code"):
|
||||
value = str(data.get(key) or "").strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
async def _platform_value(db: AsyncSession, key: str) -> str | None:
|
||||
"""平台配置直读库,不走 Redis。
|
||||
"""平台配置直读库,不走 Redis、不回退 .env。
|
||||
|
||||
配置是运维级的低频写入,读一次主键查询成本可忽略;一旦进缓存,一条写错的
|
||||
值(如文档示例 Host ``abc1234xyz.re.qweatherapi.com``)会压住库和 .env,
|
||||
|
|
@ -44,12 +61,11 @@ async def _platform_value(db: AsyncSession, key: str) -> str | 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
|
||||
key = await _platform_value(db, "qweather.key")
|
||||
host = await _platform_value(db, "qweather.host")
|
||||
if not key or not host:
|
||||
raise WeatherNotConfigured(
|
||||
"和风天气未配置:登录和风控制台 → 设置,复制账号专属 API Host"
|
||||
"(形如 abc1234xyz.re.qweatherapi.com)填入 QWEATHER_HOST 或管理端设置"
|
||||
"和风天气未配置:请在管理端「平台设置」填写 API Key 和 API Host 后保存"
|
||||
)
|
||||
h = host.strip().rstrip("/")
|
||||
if not h.startswith(("http://", "https://")):
|
||||
|
|
@ -117,14 +133,15 @@ async def _get(http: httpx.AsyncClient, url: str, params: dict[str, Any], key: s
|
|||
|
||||
resp = await http.get(url, params=params, headers=headers)
|
||||
if resp.status_code >= 400:
|
||||
raise WeatherUpstreamError(f"和风返回 HTTP {resp.status_code}")
|
||||
try:
|
||||
data = resp.json()
|
||||
except ValueError:
|
||||
data = None
|
||||
raise WeatherUpstreamError(_upstream_msg(data) or 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()
|
||||
)
|
||||
raise WeatherUpstreamError(_upstream_msg(data) or "weather upstream error")
|
||||
return data
|
||||
|
||||
|
||||
|
|
@ -161,7 +178,7 @@ def _slim(city: str, loc_id: str, now: dict[str, Any], hourly: list[dict[str, An
|
|||
|
||||
|
||||
async def is_configured(db: AsyncSession) -> bool:
|
||||
"""有效配置(管理端设置优先)是否齐备,供 /healthz 使用。"""
|
||||
"""管理端数据库配置是否齐备,供 /healthz 使用。"""
|
||||
try:
|
||||
await _conf(db)
|
||||
return True
|
||||
|
|
@ -224,6 +241,7 @@ async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
|||
out: dict[str, Any] = {
|
||||
"ok": False,
|
||||
"city": city,
|
||||
"msg": "",
|
||||
"steps": [],
|
||||
"proxy": effective_proxy(),
|
||||
"proxy_env": proxy_env(),
|
||||
|
|
@ -238,7 +256,7 @@ async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
|||
key, base = await _conf(db)
|
||||
except WeatherNotConfigured as exc:
|
||||
step("config", False, None, str(exc))
|
||||
out["hint"] = "还没配 Key/Host:到和风控制台「设置」复制账号专属 API Host 填进来"
|
||||
out["msg"] = str(exc)
|
||||
return out
|
||||
|
||||
parts = urlsplit(base)
|
||||
|
|
@ -257,7 +275,7 @@ async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
|||
step("dns", True, time.perf_counter() - t0, " ".join(ips))
|
||||
except OSError as exc:
|
||||
step("dns", False, time.perf_counter() - t0, f"{exc.__class__.__name__}: {exc}")
|
||||
out["hint"] = f"DNS 解析失败:容器里没有可用 DNS,或 Host 写错({host} 解析不到任何 IP)"
|
||||
out["msg"] = f"{exc.__class__.__name__}: {exc}"
|
||||
return out
|
||||
|
||||
# 2) TCP:这一步通过说明网络通,后面出问题都跟 Key/证书有关
|
||||
|
|
@ -267,14 +285,7 @@ async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
|||
step("tcp", True, ms, f"{ip}:{port} 建连 {ms * 1000:.0f}ms")
|
||||
except OSError as exc:
|
||||
step("tcp", False, None, f"{ip}:{port} {exc.__class__.__name__}: {exc}")
|
||||
px = out["proxy"]
|
||||
out["hint"] = (
|
||||
f"服务器到 {ip}:{port} 连不上——这是网络问题,不是配置问题。"
|
||||
+ (f"当前所有请求都发往代理 {px},先确认这个代理在服务器上活着(或删掉 *_PROXY 环境变量改成直连)。"
|
||||
if px else
|
||||
"确认服务器/容器能出网 443(安全组出站、iptables FORWARD、docker 网络),"
|
||||
"可以在宿主机上 `curl -sv https://" + host + "/` 对比一下:宿主机通、容器不通就是容器 NAT 的问题。")
|
||||
)
|
||||
out["msg"] = f"{exc.__class__.__name__}: {exc}"
|
||||
return out
|
||||
|
||||
# 3) TLS:能把 TCP 建起来但握手失败,多半是中间设备劫持或证书链缺失
|
||||
|
|
@ -290,7 +301,7 @@ async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
|||
step("tls", True, time.perf_counter() - t0, detail.strip())
|
||||
except Exception as exc: # noqa: BLE001 - 自检要兜住一切
|
||||
step("tls", False, time.perf_counter() - t0, f"{exc.__class__.__name__}: {exc}")
|
||||
out["hint"] = "TLS 握手失败:中间设备可能在做 HTTPS 拦截,或缺 CA 证书(容器里 update-ca-certificates)"
|
||||
out["msg"] = f"{exc.__class__.__name__}: {exc}"
|
||||
return out
|
||||
|
||||
# 4) 真正打一次和风接口:401/403 才是 Key/Host 的问题
|
||||
|
|
@ -302,19 +313,16 @@ async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
|||
except (WeatherUpstreamError, httpx.HTTPError) as exc:
|
||||
msg = str(exc) if isinstance(exc, WeatherUpstreamError) else explain_error(exc, base)
|
||||
step("http", False, time.perf_counter() - t0, msg)
|
||||
out["hint"] = (
|
||||
"能连上和风但被拒绝:Key 与 Host 不匹配,或 Key 已过期/项目未启用"
|
||||
if "401" in msg or "403" in msg else msg
|
||||
)
|
||||
out["msg"] = msg
|
||||
return out
|
||||
|
||||
items = data.get("location") or []
|
||||
step("http", True, time.perf_counter() - t0,
|
||||
f"HTTP 200,{city} → {items[0].get('name') if items else '(无结果)'} / {items[0].get('id') if items else '-'}")
|
||||
if not items:
|
||||
out["hint"] = f"接口通了,但查不到城市「{city}」:把常住地改成标准地名再试"
|
||||
out["msg"] = _upstream_msg(data)
|
||||
return out
|
||||
|
||||
out["ok"] = True
|
||||
out["hint"] = "一切正常:DNS、出网、证书、Key/Host 都对。设备侧没数据就是别的原因(没绑定 / 没联网 / 缓存)。"
|
||||
out["msg"] = _upstream_msg(data)
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -118,7 +118,7 @@ export type WeatherProbe = {
|
|||
resolved?: string[]
|
||||
proxy?: string
|
||||
steps: WeatherProbeStep[]
|
||||
hint?: string
|
||||
msg: string
|
||||
}
|
||||
|
||||
export type Firmware = {
|
||||
|
|
|
|||
|
|
@ -222,9 +222,7 @@ export default {
|
|||
keyTip: 'The API Key under Project → Credentials; a JWT also works',
|
||||
host: 'API Host',
|
||||
hostTip: 'Your account-specific host, from Console → Settings',
|
||||
test: 'Test connection',
|
||||
testOk: 'Connection OK',
|
||||
testFail: 'Connection failed',
|
||||
test: 'Test service',
|
||||
},
|
||||
fw: {
|
||||
statDevices: 'Devices',
|
||||
|
|
|
|||
|
|
@ -222,9 +222,7 @@ export default {
|
|||
keyTip: '控制台「项目管理 → 凭据」里的 API Key;也可以直接贴 JWT',
|
||||
host: 'API Host',
|
||||
hostTip: '账号专属域名,控制台「设置」里复制',
|
||||
test: '测试连通',
|
||||
testOk: '连通正常',
|
||||
testFail: '连通异常',
|
||||
test: '服务测试',
|
||||
},
|
||||
fw: {
|
||||
statDevices: '设备总数',
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
|
|
@ -23,7 +22,7 @@ import type { ColumnsType } from 'antd/es/table'
|
|||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import dayjs from 'dayjs'
|
||||
import { api, auth, type AdminUser, type Device, type FortuneRow, type RegionRow, type WeatherProbe, type Zodiac, type Zodiac as ZodiacType } from '../api'
|
||||
import { api, auth, type AdminUser, type Device, type FortuneRow, type RegionRow, type Zodiac, type Zodiac as ZodiacType } from '../api'
|
||||
import TopBar from '../components/TopBar'
|
||||
import {
|
||||
ChipIcon,
|
||||
|
|
@ -965,7 +964,6 @@ function SettingsPanel() {
|
|||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [ready, setReady] = useState<boolean | null>(null)
|
||||
const [probe, setProbe] = useState<WeatherProbe | null>(null)
|
||||
const [probing, setProbing] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
|
|
@ -1006,11 +1004,13 @@ function SettingsPanel() {
|
|||
}
|
||||
}
|
||||
|
||||
// 一键自检:DNS → TCP → TLS → HTTP,哪步断了一眼看得出,不用登服务器
|
||||
// 服务测试:前端只展示天气服务返回的 msg,不自行组装提示。
|
||||
async function testConn() {
|
||||
setProbing(true)
|
||||
try {
|
||||
setProbe(await api.admin.testWeather())
|
||||
const res = await api.admin.testWeather()
|
||||
if (res.ok) message.success(res.msg)
|
||||
else message.error(res.msg)
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
|
|
@ -1051,31 +1051,8 @@ function SettingsPanel() {
|
|||
<Button onClick={testConn} loading={probing} icon={<RefreshIcon size={15} />}>
|
||||
{t('admin.settings.test')}
|
||||
</Button>
|
||||
<Button type="text" onClick={load}>
|
||||
{t('common.refresh')}
|
||||
</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
|
||||
{probe && (
|
||||
<div className="probe-box">
|
||||
<Alert
|
||||
type={probe.ok ? 'success' : 'warning'}
|
||||
showIcon
|
||||
message={probe.ok ? t('admin.settings.testOk') : t('admin.settings.testFail')}
|
||||
description={probe.hint}
|
||||
/>
|
||||
<ul className="probe-steps">
|
||||
{probe.steps.map((s) => (
|
||||
<li key={s.name} className={s.ok ? 'is-ok' : 'is-bad'}>
|
||||
<span className="probe-name">{s.name.toUpperCase()}</span>
|
||||
<span className="probe-ms">{s.ms === null ? '—' : `${s.ms} ms`}</span>
|
||||
<span className="probe-detail">{s.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</Spin>
|
||||
</Card>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -919,48 +919,3 @@ body {
|
|||
}
|
||||
}
|
||||
|
||||
/* 平台设置 · 天气连通性自检(.probe-box 只在点过「测试连通」后出现) */
|
||||
.probe-box {
|
||||
margin-top: 20px;
|
||||
max-width: 480px;
|
||||
}
|
||||
.probe-steps {
|
||||
list-style: none;
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--panel);
|
||||
}
|
||||
.probe-steps li {
|
||||
display: grid;
|
||||
grid-template-columns: 52px 64px 1fr;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
border-top: 1px solid var(--line-soft);
|
||||
}
|
||||
.probe-steps li:first-child {
|
||||
border-top: none;
|
||||
}
|
||||
.probe-name {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--muted);
|
||||
}
|
||||
.probe-steps li.is-ok .probe-name {
|
||||
color: #12a150;
|
||||
}
|
||||
.probe-steps li.is-bad .probe-name {
|
||||
color: #d92d20;
|
||||
}
|
||||
.probe-ms {
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.probe-detail {
|
||||
color: var(--ink);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue