python-3.x - Django + MQTT 如何在视图中发出请求并等待响应
问题描述
我正在编写一个 django 应用程序,我需要一种方法来请求 MQTT 上的数据并等待响应(或超时)。
考虑到这样的事情:
mqtt.subscribe('response/topic')
mqtt.publish('request/topic', '{my json request message}')
for m in mqtt.on_message():
if m.payload == '......'
# OK I have response, render data from response to page, ...
# timeout could be implemented by raising exception in on_message()
我如何整合 paho mqtt?或者还有其他方法吗?我需要等待视图中几个地方的响应,一个全局on_message
回调并不是很有用。
我应该把mqtt.loop_forever()
django放在哪里?
谢谢
编辑:我的第一个解决方案是:
import queue
import paho.mqtt.client as mqtt
def mqtt_request(req_topic, resp_topic, payload, timeout=2.0):
q = queue.Queue()
def on_message(client, userdata, message):
q.put(message)
def on_connect(client, userdata, flags, rc):
c.subscribe(resp_topic)
def on_subscribe(client, userdata, mid, granted_qos):
c.publish(req_topic, payload=payload, qos=0, retain=False)
c = mqtt.Client()
c.on_message = on_message
c.on_connect = on_connect
c.on_subscribe = on_subscribe
c.connect_async('127.0.0.1')
c.loop_start()
m = None
# FIXME: it seems that there is some delay between on_message and return
# of the message...
try:
m = q.get(timeout=timeout)
except queue.Empty:
pass
c.loop_stop()
return m
鉴于用途:
r = mqtt_request('test', 'test2', 'Ahoj')
if r:
print(r.payload)
解决方案
推荐阅读
- hashicorp-vault - 续订过程中的增量不是icrement而是总TTL?
- dynamic-expresso - 如何将动态变量与匿名类型一起使用?
- visual-studio-2017 - 如何创建自己的 CUSTOM INSTALLER?
- php - 处理 PHP-FPM 和 PHP 文件设置的执行时间
- ios - 从子视图更改 UIViewController 中 UIVIew 的纵横比
- mysql - MySQL Workbench 不生成数据库
- java - Java 8 流 - 如何正确制作 NPE 安全流
- vue.js - Vue Router - 带参数的路由
- json - 如何使用 SwaggerValidator(com.atlassian.oai.validator) 在没有请求或响应的情况下验证简单的 JSON?
- mysql - 无法安装在 xampp phpmyadmin 中联合的插件