【问题标题】:Integrate Paho MQTT with Django将 Paho MQTT 与 Django 集成
【发布时间】:2018-09-04 11:39:40
【问题描述】:

我正在做一个使用 Django 和 MQTT 的项目。有一种情况,当我的 Django Web 服务器因某种原因断开连接后重新连接到代理时,我想重新订阅与数据库中的模型相关的所有主题。我的样板房如下:

class Room(models.Model):
    building    = models.ForeignKey(Building, on_delete= models.CASCADE)
    number      = models.PositiveIntegerField()
    available   = models.BooleanField(default=True)
    power       = models.BooleanField(default=False)

class Meta:
    ordering = ['building', 'number']
    unique_together = ['building', 'number']

def __str__(self):
    return f"{self.building.bid}/{self.number}"

def get_mqtt_topic(self):
    return f"{self.building.bid}/{self.number}"

get_mqtt_topic() 方法将返回与房间关联的 MQTT 主题。 MQTT客户端代码mqtt/client.py:

import paho.mqtt.client as mqtt
from .tasks import *
from .models import Room
def on_connect(client, userdata, flags, rc):
   print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc))
   room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()]
   client.subscribe(room_mqtt)

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

因为我将下面的代码放在 init.py 中,以便在与 django 应用程序不同的线程中运行 mqtt 客户端。

from mqtt.client import client

client.loop_start()

所以我收到了这个错误:django.core.exceptions.AppRegistryNotReady: 应用程序尚未加载。

【问题讨论】:

    标签: python django mqtt paho


    【解决方案1】:

    我有同样的错误,我的临时解决方案是在 on_connect 方法中导入。

    import paho.mqtt.client as mqtt
    from .tasks import *
    def on_connect(client, userdata, flags, rc):
        from .models import Room
        print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc))
        room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()]
        client.subscribe(room_mqtt)
    
    client = mqtt.Client()
    client.on_connect = on_connect
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-08
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2016-11-06
      • 1970-01-01
      • 2022-07-06
      相关资源
      最近更新 更多