在Django模板中显示MQTT数据

发布于 2025-01-21 04:23:02 字数 661 浏览 1 评论 0原文

我正在使用paho-MQTT,并且可以接收消息。当我收到一条消息时,我想在模板中显示数据,但不能这样做。以下是我拥有的代码。

import paho.mqtt.client as mqtt
import json

def on_connect(client, userdata, flags, rc):
     print("Connected with result code "+str(rc))


client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
   x = (msg.payload)
   print(x)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.eclipseprojects.io", 1883, 60)

我一直在关注

如何在创建的HTML模板中显示MQTT的新数据?

I'm using paho-MQTT and I'm able to receive messages. When I receive a message, I want to display the data in a template, but am unable to do so. Below is the code I have.

import paho.mqtt.client as mqtt
import json

def on_connect(client, userdata, flags, rc):
     print("Connected with result code "+str(rc))


client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
   x = (msg.payload)
   print(x)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.eclipseprojects.io", 1883, 60)

I have been following the tutorial.

How can I show new data from MQTT in the html template I have created?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忱杏 2025-01-28 04:23:02

这是错误的方法,但是如果它帮助某人...

from django.shortcuts import render
import paho.mqtt.client as mqtt

import json

valor_mqtt = 0

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
  global valor_mqtt
  valor_mqtt = (msg.payload)
  print(valor_mqtt)

def print_on_m(request):
  global valor_mqtt
  message = str(valor_mqtt)
  return render(request, 'home/index.html',{'context':message})



client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message


client.connect("mqtt.eclipseprojects.io", 1883, 60)

我说的是错误的方法,因为当您收到消息时,它不会实时更新模板中的值(.html)

It's the wrong way, but if it helps someone...

from django.shortcuts import render
import paho.mqtt.client as mqtt

import json

valor_mqtt = 0

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
  global valor_mqtt
  valor_mqtt = (msg.payload)
  print(valor_mqtt)

def print_on_m(request):
  global valor_mqtt
  message = str(valor_mqtt)
  return render(request, 'home/index.html',{'context':message})



client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message


client.connect("mqtt.eclipseprojects.io", 1883, 60)

I'm saying it's the wrong way because it doesn't update the value in the template(.html) in real time when you get a message

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文