I am writing a django application which should act as MQTT publisher and as a subscriber.
Where should I start the paho client and run loop_forever() function.
Should it be in wsgi.py ?
I am writing a django application which should act as MQTT publisher and as a subscriber.
Where should I start the paho client and run loop_forever() function.
Should it be in wsgi.py ?
Update:
If you need Django running in multiple threads then to publish messages from your Django app you can use helper functions from Publish module of Paho - https://eclipse.org/paho/clients/python/docs/#id17 You don't need to create an instance of mqtt client and start a loop in this case. And to subscribe to some topic consider running mqtt client as a standalone script and import there needed modules of your Django app (and don't forget to setup the Django environment in the script).
The answer below is good only if you run Django in a single thread, which is not usual in production.
Create
mqtt.py
in your application folder and put all related code there. For example:Don't call
loop_forever()
here!Then in your application
__init__.py
callloop_start()
:Using
loop_start()
instead ofloop_forever()
will give you not blocking background thread.