我正在使用Django和MQTT客户端。我想在Django应用就绪后立即在后台运行MQTT客户端,并在客户端运行,所以我有以下代码:
###mysite/app/apps.py
from django.apps import AppConfig
class TimetableConfig(AppConfig):
name = 'timetable'
def ready(self):
from mqtt.client import client
client.loop_start()
###mysite/mqtt/client
import paho.mqtt.client as mqtt
#from .tasks import *
#The callback for connecting to CloudMQTT broker
def on_connect(client, userdata, flags, rc):
print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '"
+ message.topic + "' with QoS " + str(message.qos))
topic = message.topic.split('/')
room = get_room(topic[0], int(topic[1]))
if topic[2] == 'ID':
pass
if topic[2] == 'lastWill':
pass
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set('xxxxxxxx', 'xxxxxxxx')
client.connect('xxxxxxxx', xxxxx),
第二个代码是从apps.py中导入客户端对象的位置。启动开发服务器时,为什么不创建两个MQTT客户端?