【发布时间】: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: 应用程序尚未加载。
【问题讨论】: