## 后端
- 新增 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 通过。
173 lines
7.3 KiB
Python
173 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""步行路线:百度轻量级路线规划 + 缓存 + 估算兜底。"""
|
|
import json
|
|
import os
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import Mock, patch
|
|
|
|
import walk_route
|
|
|
|
ORIGIN = (36.529440, 116.783740)
|
|
DEST = (36.534240, 116.787190)
|
|
|
|
|
|
class EstimateTests(unittest.TestCase):
|
|
def test_straight_line_is_expanded_by_detour_factor(self):
|
|
got = walk_route.estimate(*ORIGIN, *DEST)
|
|
self.assertEqual("estimate", got["source"])
|
|
# 直线约 615 米 -> 乘 1.3 绕行系数
|
|
self.assertGreater(got["straight"], 550)
|
|
self.assertLess(got["straight"], 700)
|
|
self.assertAlmostEqual(got["distance"], got["straight"] * 1.3, delta=2)
|
|
# 75 米/分钟
|
|
self.assertAlmostEqual(got["duration"], got["distance"] / 75 * 60, delta=2)
|
|
|
|
def test_bad_input_never_raises(self):
|
|
for args in ((None, None, None, None), ("a", "b", "c", "d")):
|
|
self.assertEqual("none", walk_route.estimate(*args)["source"])
|
|
|
|
|
|
class QueryAndSnTests(unittest.TestCase):
|
|
PARAMS = {"ak": "X", "origin": "36.5,116.7", "destination": "36.4,116.6",
|
|
"coord_type": "gcj02"}
|
|
|
|
def test_without_sk_no_sn(self):
|
|
q = walk_route.build_query(self.PARAMS, "")
|
|
self.assertNotIn("sn=", q)
|
|
self.assertIn("coord_type=gcj02", q)
|
|
|
|
def test_two_sn_modes_differ_and_are_deterministic(self):
|
|
a1 = walk_route.build_query(self.PARAMS, "SK", "official")
|
|
a2 = walk_route.build_query(self.PARAMS, "SK", "official")
|
|
b = walk_route.build_query(self.PARAMS, "SK", "simple")
|
|
self.assertEqual(a1, a2)
|
|
self.assertIn("sn=", a1)
|
|
self.assertIn("sn=", b)
|
|
self.assertNotEqual(a1.split("sn=")[1], b.split("sn=")[1])
|
|
|
|
def test_params_are_key_sorted(self):
|
|
q = walk_route.build_query(self.PARAMS, "")
|
|
keys = [part.split("=")[0] for part in q.split("&")]
|
|
self.assertEqual(sorted(keys), keys)
|
|
|
|
|
|
class GetWalkRouteTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.path = Path(self.tmp.name) / "walk_cache.db"
|
|
self.patches = [
|
|
patch.object(walk_route, "CACHE_PATH", self.path),
|
|
patch.object(walk_route, "_cache_ready", [False]),
|
|
patch.object(walk_route, "_last_call_at", [0.0]),
|
|
patch.object(walk_route, "MIN_INTERVAL_SECONDS", 0.0),
|
|
]
|
|
for p in self.patches:
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
|
|
def _ok(self):
|
|
resp = Mock()
|
|
resp.raise_for_status = Mock()
|
|
resp.json = Mock(return_value={"status": 0, "result": {"routes": [
|
|
{"distance": 820, "duration": 640}]}})
|
|
return resp
|
|
|
|
def test_without_ak_returns_estimate_and_never_calls_bbox(self):
|
|
with patch.object(walk_route, "get_ak", return_value=""), \
|
|
patch("walk_route.requests.get") as http:
|
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
self.assertEqual("estimate", got["source"])
|
|
http.assert_not_called()
|
|
|
|
def test_baidu_success_then_served_from_cache(self):
|
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
|
patch.object(walk_route, "get_sk", return_value=""), \
|
|
patch("walk_route.requests.get", return_value=self._ok()) as http:
|
|
first = walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
second = walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
self.assertEqual("baidu", first["source"])
|
|
self.assertEqual(820, first["distance"])
|
|
self.assertEqual(640, first["duration"])
|
|
self.assertEqual("cache", second["source"])
|
|
self.assertEqual(1, http.call_count) # 第二次没再打百度
|
|
|
|
def test_coord_type_is_gcj02(self):
|
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
|
patch.object(walk_route, "get_sk", return_value=""), \
|
|
patch("walk_route.requests.get", return_value=self._ok()) as http:
|
|
walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
url = http.call_args[0][0]
|
|
self.assertIn("coord_type=gcj02", url)
|
|
self.assertIn("directionlite/v1/walking", url)
|
|
|
|
def test_sn_failure_retries_the_other_mode(self):
|
|
bad = Mock()
|
|
bad.raise_for_status = Mock()
|
|
bad.json = Mock(return_value={"status": 211, "message": "APP SN校验失败"})
|
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
|
patch.object(walk_route, "get_sk", return_value="SK"), \
|
|
patch.object(walk_route, "_SN_MODE", [None]), \
|
|
patch("walk_route.requests.get", side_effect=[bad, self._ok()]) as http:
|
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
self.assertEqual("baidu", got["source"])
|
|
self.assertEqual(2, http.call_count) # 官方算法失败后换了另一种
|
|
|
|
def test_app_disabled_falls_back_without_retry(self):
|
|
bad = Mock()
|
|
bad.raise_for_status = Mock()
|
|
bad.json = Mock(return_value={"status": 240, "message": "APP 服务被禁用"})
|
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
|
patch.object(walk_route, "get_sk", return_value="SK"), \
|
|
patch("walk_route.requests.get", return_value=bad) as http:
|
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
self.assertEqual("estimate", got["source"])
|
|
self.assertEqual(1, http.call_count) # 240 不是 SN 问题,不重试
|
|
|
|
def test_network_error_falls_back(self):
|
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
|
patch.object(walk_route, "get_sk", return_value=""), \
|
|
patch("walk_route.requests.get", side_effect=TimeoutError("boom")):
|
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
|
self.assertEqual("estimate", got["source"])
|
|
self.assertGreater(got["distance"], 0)
|
|
|
|
|
|
class CredentialStorageTests(unittest.TestCase):
|
|
"""管理端回显:SK 不能明文吐给前端。"""
|
|
|
|
def test_masked_hides_sk(self):
|
|
with patch.object(walk_route, "get_ak", return_value="AK123"), \
|
|
patch.object(walk_route, "get_sk", return_value="SK-abcdef1234"):
|
|
got = walk_route.masked_credentials()
|
|
self.assertEqual("AK123", got["ak"])
|
|
self.assertTrue(got["sk_set"])
|
|
self.assertEqual("1234", got["sk_tail"])
|
|
self.assertNotIn("SK-abcdef", str(got))
|
|
|
|
def test_masked_when_empty(self):
|
|
with patch.object(walk_route, "get_ak", return_value=""), \
|
|
patch.object(walk_route, "get_sk", return_value=""):
|
|
got = walk_route.masked_credentials()
|
|
self.assertFalse(got["enabled"])
|
|
self.assertFalse(got["sk_set"])
|
|
|
|
|
|
class DoublePrecisionCacheKeyTests(unittest.TestCase):
|
|
def test_nearby_points_share_a_cache_key(self):
|
|
a = walk_route._cache_key(36.529441, 116.783741, 36.534239, 116.787191)
|
|
b = walk_route._cache_key(36.529444, 116.783744, 36.534241, 116.787194)
|
|
self.assertEqual(a, b) # 10 米内视作同一对起终点
|
|
|
|
def test_far_points_differ(self):
|
|
a = walk_route._cache_key(36.5294, 116.7837, 36.5342, 116.7872)
|
|
b = walk_route._cache_key(36.5394, 116.7937, 36.5342, 116.7872)
|
|
self.assertNotEqual(a, b)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|