当自动爬取的时候前端没有传输设备绑定和iccid的关系,导致后端没有接收到,现在修改逻辑
This commit is contained in:
@ -109,7 +109,29 @@ def auto_monitor_job(app):
|
||||
device.current_value = item.get('value')
|
||||
device.latest_time = item.get('target_time')
|
||||
device.check_time = current_time
|
||||
device.json_data = json.dumps(item.get('raw_json', {}), ensure_ascii=False)
|
||||
|
||||
# =========== ✅ 核心修复开始:防止丢失 bound_iccid ===========
|
||||
|
||||
# 1. 准备容器:先读取数据库里现有的 JSON 数据
|
||||
old_json = {}
|
||||
try:
|
||||
if device.json_data:
|
||||
old_json = json.loads(device.json_data)
|
||||
except Exception:
|
||||
old_json = {}
|
||||
|
||||
# 2. 获取爬虫新数据
|
||||
new_json = item.get('raw_json', {})
|
||||
|
||||
# 3. 合并数据:只更新新爬取到的字段,保留 old_json 里的 bound_iccid
|
||||
if isinstance(new_json, dict):
|
||||
old_json.update(new_json)
|
||||
|
||||
# 4. 存回数据库
|
||||
device.json_data = json.dumps(old_json, ensure_ascii=False)
|
||||
|
||||
# =========== ✅ 核心修复结束 ===========
|
||||
|
||||
device.offset = calculate_offset(item.get('target_time'))
|
||||
|
||||
db.session.add(DeviceHistory(
|
||||
@ -125,28 +147,8 @@ def auto_monitor_job(app):
|
||||
print("⚠️ [定时任务-爬虫] 未获取到数据")
|
||||
except Exception as e:
|
||||
print(f"❌ [定时任务-爬虫] 异常: {e}")
|
||||
|
||||
# --- 任务 B: IoT 同步 ---
|
||||
if sync_iot_data_service:
|
||||
try:
|
||||
# 1. 获取数据
|
||||
iot_list = sync_iot_data_service()
|
||||
# 2. 保存入库 (复用 api.py 中的逻辑)
|
||||
count_iot, err = save_iot_cards_to_db(iot_list)
|
||||
if err:
|
||||
print(f"❌ [定时任务-IoT] 错误: {err}")
|
||||
else:
|
||||
print(f"✅ [定时任务-IoT] 更新 {count_iot} 张")
|
||||
except Exception as e:
|
||||
print(f"❌ [定时任务-IoT] 异常: {e}")
|
||||
|
||||
# 统一提交事务
|
||||
try:
|
||||
db.session.commit()
|
||||
print("💾 [定时任务] 数据库事务提交完成")
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"❌ [定时任务] 提交失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
|
||||
Reference in New Issue
Block a user