如何更新Django模板中的MQTT数据
我正在使用PAHO-MQTT,可以接收消息,并且可以在模板(HTML)中显示数据,但是我无法在模板(HTML)中实时更新消息。当我从蚊子/主题中获取新消息时,我想更新模板中的值。
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)
我正在urls.py中传递print_on_m,以在home/index.html中使用{{context}}以显示数据
ps:我不想使用“ setInterval(function(function(){”或“ .load( window.location.href“一段时间后更新网页的一部分,我只想在从蚊子/主题中获取新消息时进行更新
I'm using paho-MQTT and I can receive messages and I can display the data in a template(html), but I can't update the message in realtime in the template(html). I want to update the value in the template when I get a new message from the mosquitto/topic.
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 passing print_on_m in urls.py to use {{context}} in home/index.html to show the data
PS: I don't want to use functions like "setInterval(function() {" or ".load(window.location.href" to update part of the web page after some time, I want to update only when I get new message from mosquitto/topic
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

简短的答案是您不在Django中这样做。
该模板仅在服务器端渲染一次,然后发送到客户端,一旦发送就无法更新。
您可以做的是,如果您的经纪人支持MQTT在Websockets上支持MQTT,则可以使用PAHO JAVASCRIPT客户端或MQTT.JS客户端从浏览器中运行的页面中订阅经纪人,然后直接获取更新,然后相应地更新页面。
The short answer is you don't do it in django.
The template is only rendered once on the server side then sent to the client, it can't be updated once sent.
What you can do is if your broker supports MQTT over WebSockets then you can use either the Paho JavaScript client or the MQTT.js client to subscribe to the broker from within the page running in the browser and get updates directly then update the page accordingly.