如何在Django中使用Paho MQTT Client? [英] How to use paho mqtt client in django?
问题描述
我正在编写一个Django应用程序,该应用程序应充当MQTT发布者和订阅者.
I am writing a django application which should act as MQTT publisher and as a subscriber.
我应该在哪里启动paho客户端并运行loop_forever()函数.
Where should I start the paho client and run loop_forever() function.
应该在wsgi.py中吗?
Should it be in wsgi.py ?
推荐答案
更新:
如果您需要在多个线程中运行Django,然后要从Django应用程序发布消息,则可以使用Paho的Publish模块中的帮助程序功能-
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).
仅当您在单个线程中运行Django(在生产环境中并不常见)时,以下答案才是好的.
在您的应用程序文件夹中创建mqtt.py
,并将所有相关代码放在此处.例如:
Create mqtt.py
in your application folder and put all related code there. For example:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, rc):
client.subscribe("$SYS/#")
def on_message(client, userdata, msg):
# Do something
pass
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
请勿在此处致电loop_forever()
!
Don't call loop_forever()
here!
然后在您的应用程序__init__.py
中调用loop_start()
:
Then in your application __init__.py
call loop_start()
:
from . import mqtt
mqtt.client.loop_start()
使用loop_start()
代替loop_forever()
将使您不会阻塞后台线程.
Using loop_start()
instead of loop_forever()
will give you not blocking background thread.
这篇关于如何在Django中使用Paho MQTT Client?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!