Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import json
import paho.mqtt.client as mqtt
from django.http import JsonResponse
def get_product_details(request, product_id):
try:
# 连接到 MQTT 服务器
mqtt_client = mqtt.Client()
mqtt_client.connect("mqtt.eclipse.org", 1883, 60) # 这里使用了一个公共的 MQTT 服务器,你也可以使用自己的服务器
# 定义订阅主题
topic = f"product/{product_id}/details"
# 定义回调函数处理收到的消息
def on_message(client, userdata, msg):
product_details = json.loads(msg.payload.decode())
# 在这里你可以根据需要对收到的商品详细信息进行处理,比如存储到数据库或直接返回给前端
mqtt_client.disconnect() # 收到消息后断开连接
# 返回商品详细信息
return JsonResponse(product_details)
# 订阅主题并设置回调函数
mqtt_client.subscribe(topic)
mqtt_client.on_message = on_message
# 开始 MQTT 客户端的循环,处理消息
mqtt_client.loop_start()
# 等待收到消息,这里可以设置一个超时时间
mqtt_client.loop_timeout(2) # 等待 2 秒
# 如果超时仍未收到消息,返回空的商品详情
return JsonResponse({}) # 这里根据你的需要返回适当的响应数据格式
except Exception as e:
# 处理连接异常或其他错误情况
return JsonResponse({"error": str(e)})