fix: 优化更新逻辑,添加异常处理

This commit is contained in:
fxxian 2024-03-25 21:35:03 +08:00
parent 656e062040
commit ff51c50a4f
1 changed files with 14 additions and 6 deletions

View File

@ -1,12 +1,18 @@
import json
import os
import sys
import json
import django
from typing import Dict
from pathlib import Path
from enum import Enum
import paho.mqtt.client as mqtt
pwd = os.path.dirname(os.path.realpath(__file__))
project_path = Path(pwd).parent.parent
if project_path not in sys.path:
sys.path.append(str(project_path))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mosqkiller.settings")
django.setup()
@ -37,15 +43,17 @@ def on_message(client, userdata, message):
topic_parts = topic.split('/')
device_id = topic_parts[2]
# 将消息打印到控制台(或处理数据,例如存入数据库)
print(f"Device: {device_id} update & create post")
payload = message.payload.decode('utf-8')
# print(f"Message Payload: {payload}")
# update and create
post_data = json.loads(payload)
update_device_info(device_id, post_data=post_data)
create_mosq_post(device_id, post_data=post_data)
try:
update_device_info(device_id, post_data=post_data)
create_mosq_post(device_id, post_data=post_data)
print(f"Device: {device_id} update & create post success")
except KeyError:
print(f"Device: {device_id} update & create post failed")
print(payload)
def update_device_info(device_id: str, post_data: Dict):