Files
xbcr/walk_route.py
T
zzy bd41866a3d feat: 步行距离改用百度轻量级路线规划(真实道路距离 + 耗时)
## 后端
- 新增 walk_route.py:调 directionlite/v1/walking,coord_type=gcj02(与上游车辆同坐标系)
  - AK 开了 SN 校验时自动带 timestamp 并按 SN 规则签名;官方样例与社区两种算法都实现,
    211 时自动换另一种(实测:官方算法 + timestamp 可通过)
  - 结果按起终点(4 位小数)缓存 7 天;按 3 QPS 配额做 350ms 节流
  - 没配 AK / 240 / 超时 / 配额用尽一律退回本地估算(直线 ×1.3,75 米/分钟),卡片不会空
- 新增 /api/walk_route(需登录,按 IP 60 次/分钟限流)
- 管理端新增 /api/admin/route_key(GET 回显,SK 只给尾号)、POST 保存、POST 测试连通

## 前端
- 车辆卡片:先显示直线估算,再异步换成真实道路距离与耗时
  顺序:后端接口(有 AK 时,命中缓存最快)→ 浏览器端 BMapGL.WalkingRoute(现成浏览器 AK)
  → 都失败则保留直线估算。解析 SDK 返回的「1.6公里 / 23分钟」字符串。
- 管理后台顶部新增「🚶 步行路线 AK」按钮 + 配置弹窗(保存 / 测试连通 / 清空 SK)

## 配置
- server_config.json: baidu_route_ak / baidu_route_sk(已 gitignore)
- 或环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK

实测(校内两点):直线 615 米 -> 百度 1015 米 / 868 秒(14.5 分钟)。
新增 tests/test_walk_route.py(15 条);全量 136 pytest + 29 node 通过。
2026-11-14 20:31:43 +08:00

312 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""百度「步行路线规划(轻量)」:真实道路距离 + 步行耗时。
为什么要它:卡片原来只会拿直线距离 ÷ 80 米/分钟估时间,绕楼绕围墙时明显偏乐观。
百度轻量级路线规划接口(directionlite)直接给 `distance`(米)和 `duration`(秒),
且支持 `coord_type=gcj02` —— 正好和上游车辆坐标同一套,不用转换。
配额与限流(2026-11 实测控制台:0.5 万次/天,3 QPS):
- 结果按「起点+终点」四舍五入到 4 位小数(约 10 米)入库缓存 7 天;
- 进程内做 3 QPS 节流(保守取 350ms 间隔);
- 任何失败(没配 AK / 240 APP 服务被禁用 / 超时 / 配额耗尽)都退回本地估算,
绝不让卡片空着。
配置(缺一即走估算):
- 环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK
- 或 server_config.json 里的 "baidu_route_ak" / "baidu_route_sk"
注意:
- 必须用**服务端**类型的 AK,且开通「步行路线规划(轻量)」;
- 页面里那个浏览器端 AK 调这个接口会返回 {"status":240,"message":"APP 服务被禁用"}(已实测);
- 若该 AK 在控制台开了「SN 校验」,请求必须带 sn(否则 211),所以需要配套的 SK,
见 `_build_query()`。
"""
import hashlib
import json
import math
import os
import sqlite3
import threading
import time
from pathlib import Path
from urllib.parse import quote, quote_plus, urlencode
import requests
HOST = "https://api.map.baidu.com"
PATH = "/directionlite/v1/walking"
BASE_URL = HOST + PATH
CACHE_PATH = Path(__file__).parent / "walk_cache.db"
CACHE_TTL_SECONDS = 7 * 24 * 3600
# 坐标精度:4 位小数 ≈ 11 米,够用且能显著提高缓存命中率
COORD_PRECISION = 4
# 3 QPS 配额,保守按 350ms 一次
MIN_INTERVAL_SECONDS = 0.35
REQUEST_TIMEOUT = 6
# 本地估算参数(百度不可用时兜底)
DETOUR_FACTOR = 1.3 # 直线 -> 道路的经验绕行系数
WALK_METERS_PER_MIN = 75.0 # 4.5 km/h
_lock = threading.Lock()
_last_call_at = [0.0]
_cache_ready = [False]
# ========== 配置 ==========
def _server_config() -> dict:
try:
path = Path(__file__).parent / "server_config.json"
if path.exists():
return json.loads(path.read_text("utf-8"))
except Exception:
pass
return {}
def get_ak() -> str:
"""服务端 AK:环境变量优先,其次 server_config.json 的 baidu_route_ak。"""
env = (os.environ.get("BAIDU_ROUTE_AK") or "").strip()
if env:
return env
return str(_server_config().get("baidu_route_ak") or "").strip()
def get_sk() -> str:
"""SN 校验用的 SK(私钥)。AK 未开 SN 校验时可以留空。"""
env = (os.environ.get("BAIDU_ROUTE_SK") or "").strip()
if env:
return env
return str(_server_config().get("baidu_route_sk") or "").strip()
def is_enabled() -> bool:
return bool(get_ak())
def save_credentials(ak: str, sk: str = None) -> bool:
"""把 AK/SK 写进 server_config.json(管理端弹窗用)。
sk 传 None 表示保持原值不动;传 "" 表示清空。
"""
path = Path(__file__).parent / "server_config.json"
try:
cfg = {}
if path.exists():
cfg = json.loads(path.read_text("utf-8")) or {}
cfg["baidu_route_ak"] = (ak or "").strip()
if sk is not None:
cfg["baidu_route_sk"] = (sk or "").strip()
path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
return True
except Exception as exc:
print(f"[步行路线] 保存 AK/SK 失败: {exc}")
return False
def masked_credentials() -> dict:
"""给管理端回显用:AK 全量(管理员要看),SK 只回显尾 4 位。"""
ak = get_ak()
sk = get_sk()
return {"ak": ak, "sk_set": bool(sk),
"sk_tail": sk[-4:] if sk else "", "enabled": bool(ak)}
def build_query(params: dict, sk: str = "", mode: str = "official") -> str:
"""按百度 SN 规则拼查询串。
百度官方样例(geocoder/v2 那份)与社区常见写法算出的 sn 不一致,
没有 SK 无法判定哪个对,所以两种都实现,由上层自动试:
- official:quote("path?query", safe=...) -> 追加 SK -> quote_plus -> md5
- simple :urlencode(按 key 升序, safe="") -> md5("path?query" + SK)
"""
items = sorted((k, v) for k, v in params.items() if k != "sn")
if mode == "simple":
query = urlencode(items, encoding="utf-8", safe="")
if not sk:
return query
digest = hashlib.md5((PATH + "?" + query + sk).encode("utf-8")).hexdigest()
return query + "&sn=" + digest
raw_query = "&".join(f"{k}={v}" for k, v in items)
encoded = quote(PATH + "?" + raw_query, safe="/:=&?#+!$,;'@()*[]")
query = encoded[len(PATH) + 1:]
if not sk:
return query
digest = hashlib.md5(quote_plus(encoded + sk).encode("utf-8")).hexdigest()
return query + "&sn=" + digest
# 记住哪种 SN 算法能通,避免每次先撞一次 211
_SN_MODE = [None]
def _sn_modes():
if _SN_MODE[0]:
other = "simple" if _SN_MODE[0] != "simple" else "official"
return [_SN_MODE[0], other]
return ["official", "simple"]
# ========== 缓存 ==========
def _conn():
conn = sqlite3.connect(CACHE_PATH, timeout=5)
if not _cache_ready[0]:
conn.execute("""
CREATE TABLE IF NOT EXISTS walk_cache (
key TEXT PRIMARY KEY,
distance_m INTEGER NOT NULL,
duration_s INTEGER NOT NULL,
created_at REAL NOT NULL
)
""")
conn.commit()
_cache_ready[0] = True
return conn
def _cache_key(o_lat, o_lng, d_lat, d_lng) -> str:
p = COORD_PRECISION
return "%.*f,%.*f|%.*f,%.*f" % (p, o_lat, p, o_lng, p, d_lat, p, d_lng)
def _cache_get(key):
try:
conn = _conn()
row = conn.execute(
"SELECT distance_m, duration_s, created_at FROM walk_cache WHERE key = ?",
(key,)).fetchone()
conn.close()
if not row:
return None
if time.time() - float(row[2]) > CACHE_TTL_SECONDS:
return None
return {"distance": int(row[0]), "duration": int(row[1])}
except Exception as exc:
print(f"[步行路线] 读缓存失败: {exc}")
return None
def _cache_put(key, distance_m, duration_s):
try:
conn = _conn()
conn.execute(
"INSERT OR REPLACE INTO walk_cache (key, distance_m, duration_s, created_at) "
"VALUES (?, ?, ?, ?)", (key, int(distance_m), int(duration_s), time.time()))
conn.commit()
conn.close()
except Exception as exc:
print(f"[步行路线] 写缓存失败: {exc}")
# ========== 节流 ==========
def _throttle():
"""全局 3 QPS 上限(百度给的并发就是 3)。"""
with _lock:
wait = _last_call_at[0] + MIN_INTERVAL_SECONDS - time.time()
if wait > 0:
time.sleep(wait)
_last_call_at[0] = time.time()
# ========== 估算兜底 ==========
def estimate(origin_lat, origin_lng, dest_lat, dest_lng) -> dict:
"""直线 → 道路经验估算。永远有返回值。"""
try:
lat1, lng1, lat2, lng2 = map(float, (origin_lat, origin_lng, dest_lat, dest_lng))
except (TypeError, ValueError):
return {"distance": 0, "duration": 0, "source": "none"}
r = 6371000.0
p1, p2 = math.radians(lat1), math.radians(lat2)
dphi = p2 - p1
dlmb = math.radians(lng2 - lng1)
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
straight = 2 * r * math.asin(math.sqrt(a))
distance = int(round(straight * DETOUR_FACTOR))
duration = int(round(max(distance, 1) / WALK_METERS_PER_MIN * 60))
return {"distance": distance, "duration": duration, "straight": int(round(straight)),
"source": "estimate"}
# ========== 百度接口 ==========
def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
mode="official") -> dict:
_throttle()
params = {
"ak": ak,
"origin": f"{origin_lat:.6f},{origin_lng:.6f}",
"destination": f"{dest_lat:.6f},{dest_lng:.6f}",
"coord_type": "gcj02", # 上游车辆坐标就是 GCJ02,不用转
}
if sk:
# 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset)
params["timestamp"] = int(time.time())
url = BASE_URL + "?" + build_query(params, sk, mode)
resp = requests.get(url, timeout=REQUEST_TIMEOUT)
resp.raise_for_status()
data = resp.json()
status = data.get("status")
if status != 0:
raise RuntimeError(f"status={status} message={data.get('message')}")
result = data.get("result") or {}
# directionlite 正常返回 result.routes[0].{distance,duration};
# 少数版本把 distance/duration 直接挂在 result 上,一并兜住。
route = (result.get("routes") or [{}])[0]
distance = route.get("distance", result.get("distance"))
duration = route.get("duration", result.get("duration"))
if distance is None or duration is None:
raise RuntimeError(f"返回缺字段: {str(data)[:200]}")
return {"distance": int(distance), "duration": int(duration)}
def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict:
"""返回 {distance(米), duration(秒), source: baidu|cache|estimate}。
source=cache 也代表数据来自百度(命中缓存)。
"""
try:
o_lat, o_lng = float(origin_lat), float(origin_lng)
d_lat, d_lng = float(dest_lat), float(dest_lng)
except (TypeError, ValueError):
return estimate(origin_lat, origin_lng, dest_lat, dest_lng)
if not (math.isfinite(o_lat) and math.isfinite(o_lng)
and math.isfinite(d_lat) and math.isfinite(d_lng)):
return estimate(o_lat, o_lng, d_lat, d_lng)
key = _cache_key(o_lat, o_lng, d_lat, d_lng)
if use_cache:
hit = _cache_get(key)
if hit:
return {**hit, "source": "cache"}
ak = get_ak()
if not ak:
return estimate(o_lat, o_lng, d_lat, d_lng)
sk = get_sk()
got = None
last_error = None
for mode in _sn_modes():
try:
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode)
_SN_MODE[0] = mode # 记住能通的算法
break
except Exception as exc:
last_error = exc
text = str(exc)
# 只有 SN 相关错误才值得换算法重试,其余(配额/超时)直接退回估算
if "211" not in text and "SN" not in text.upper():
break
if got is None:
print(f"[步行路线] 百度调用失败,退回估算: {last_error}")
return estimate(o_lat, o_lng, d_lat, d_lng)
_cache_put(key, got["distance"], got["duration"])
return {**got, "source": "baidu"}