功能:区域绑定工单链路 + Edge API 认证
1. Edge Token 认证:edge_compat.py 新增 _verify_edge_token 依赖, 通过 EDGE_AUTH_TOKEN 环境变量配置共享 Token,保护告警上报接口 2. 区域列表 API:新增 /api/area/list 代理查询 IoT 平台区域数据, 供前端摄像头页面选择区域使用(带 5 分钟缓存) 3. 降级查询:notify_dispatch.py 中 area_id 为空时从 WVP API 查询兜底 4. 配置新增:EdgeAuthConfig(token + enabled)、IotDbConfig
This commit is contained in:
89
app/routers/area_api.py
Normal file
89
app/routers/area_api.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
区域列表 API
|
||||
|
||||
代理查询 IoT 平台的区域数据,供前端摄像头页面选择区域使用。
|
||||
带 5 分钟缓存,减少跨服务查询。
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.config import settings
|
||||
from app.yudao_compat import YudaoResponse
|
||||
from app.utils.logger import logger
|
||||
|
||||
router = APIRouter(prefix="/api/area", tags=["区域管理"])
|
||||
|
||||
# 区域列表缓存
|
||||
_area_list_cache: Dict[str, Any] = {"data": [], "expire": 0}
|
||||
_CACHE_TTL = 300 # 5 分钟
|
||||
|
||||
|
||||
async def _fetch_area_list_from_iot() -> List[Dict]:
|
||||
"""从 IoT 平台获取区域列表"""
|
||||
import httpx
|
||||
|
||||
base_url = (
|
||||
os.getenv("IOT_PLATFORM_URL", "")
|
||||
or settings.work_order.base_url
|
||||
)
|
||||
if not base_url:
|
||||
logger.warning("未配置 IoT 平台地址,无法查询区域列表")
|
||||
return []
|
||||
|
||||
# 复用 notify_dispatch 中的 token 缓存
|
||||
from app.services.notify_dispatch import _iot_token_cache
|
||||
|
||||
now = time.time()
|
||||
if not _iot_token_cache["token"] or now > _iot_token_cache["expire"]:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
login_resp = await client.post(
|
||||
f"{base_url}/admin-api/system/auth/login",
|
||||
json={"username": "admin", "password": "admin123", "tenantName": "默认"},
|
||||
headers={"tenant-id": "1"},
|
||||
)
|
||||
login_data = login_resp.json().get("data", {})
|
||||
_iot_token_cache["token"] = login_data.get("accessToken", "")
|
||||
_iot_token_cache["expire"] = now + 1200
|
||||
|
||||
token = _iot_token_cache["token"]
|
||||
if not token:
|
||||
return []
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.get(
|
||||
f"{base_url}/admin-api/ops/area/list",
|
||||
headers={"tenant-id": "1", "Authorization": f"Bearer {token}"},
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get("code") == 0 and data.get("data"):
|
||||
return data["data"]
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
async def get_area_list():
|
||||
"""
|
||||
获取区域列表(从 IoT 平台代理查询,带 5 分钟缓存)
|
||||
|
||||
返回: [{id, areaName, parentId, ...}]
|
||||
"""
|
||||
now = time.time()
|
||||
if _area_list_cache["data"] and now < _area_list_cache["expire"]:
|
||||
return YudaoResponse.success(_area_list_cache["data"])
|
||||
|
||||
try:
|
||||
areas = await _fetch_area_list_from_iot()
|
||||
if areas:
|
||||
_area_list_cache["data"] = areas
|
||||
_area_list_cache["expire"] = now + _CACHE_TTL
|
||||
return YudaoResponse.success(areas)
|
||||
except Exception as e:
|
||||
logger.error(f"获取区域列表失败: {e}", exc_info=True)
|
||||
# 有旧缓存则返回旧数据
|
||||
if _area_list_cache["data"]:
|
||||
return YudaoResponse.success(_area_list_cache["data"])
|
||||
return YudaoResponse.error(500, f"获取区域列表失败: {e}")
|
||||
Reference in New Issue
Block a user