Update:
If you need to run Django in multiple threads to publish messages from your Django application, you can use the helper functions from the Paho publishing module - https://eclipse.org/paho/clients/python/docs/#id17
You do not need to instantiate mqtt client and run the loop in this case. And to subscribe to some topic, consider starting the mqtt client as a stand-alone script and import the necessary modules of your Django application (and do not forget to configure the Django environment in the script).
The answer below is only good when starting Django in a single thread, which is not common in production.
Create mqtt.pyin your application folder and put all the related codes there. For instance:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, rc):
client.subscribe("$SYS/#")
def on_message(client, userdata, msg):
pass
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
Do not call loop_forever()here!
__init__.py loop_start():
from . import mqtt
mqtt.client.loop_start()
loop_start() loop_forever() .