[英]Implementing MQTT in flask
我想問一個關於如何在flask中實現mqtt的問題。 我寫了一些代碼,當我轉到特定頁面時,它將接收消息,並將其存儲在數據庫中,然后將消息輸出到該特定頁面的表中。
以下是我的代碼段。
'views.py'
from flask import render_template, request, url_for, redirect, flash
from flask_wtf import Form
from flask_login import login_user, logout_user, login_required
import paho.mqtt.client as mqtt
from app import app, db
from models import User, Data
...other @app.route...
@app.route('/table')
@login_required
def table_data():
def on_connect(client, userdata, flags, rc):
flash("connected")
client.subscribe("abc123")
def on_message(client, userdata, msg, message):
message = Data(temperature=msg.temperature, ph=msg.pH, time=msg.time)
db.session.add(message)
db.session.commit()
client = mqtt.Client(client_id = "my_visualise", clean_session = True)
client.username_pw_set("mosquitto", "mosquitto")
client.on_connect = on_connect
client.on_message = on_message
return render_template('table_data.html')
'models.py'
from app import app, db
...User table...
# Data table
class Data(db.Model):
__tablename__= 'data_reading'
id = db.Column(db.Integer, primary_key=True)
temperature = db.Column(db.Integer, index=True)
pH = db.Column(db.Integer, index=True)
time = db.Column(db.DateTime, index=True)
def __init__(self, temperature, pH, time):
self.temperature = temperature
self.pH = pH
self.time = time
db.create_all()
'table_data.html'
...
<div class="jumbotron">
<div class="container-fluid">
<h2>Data</h2>
<p>This table includes the data for temperature, pH value and time</p>
<div class="table-responsive">
<table class="table", border=2>
{% for value in message.iteritems() %}
<thead>
<tr>
<th>id</th>
<th>Temperature</th>
<th>pH Value</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
<tr>
<td> {{value}} </td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</div>
我在計算機上本地運行代碼。 起初沒有錯誤,但是一旦我進入頁面'/ table',我看到以下錯誤。
'錯誤'
UndefinedError: 'message' is undefined
我認為這可能是我在“ views.py”中編寫腳本的方式所存在的問題,因為我沒有找到足以理解並在燒瓶中實現mqtt的示例或教程。 因此,我決定嘗試自己實施。
我想問一下您對此的看法。
提前致謝。
我對flask不夠了解,無法給出一個有效的示例,但是您需要將所有mqtt代碼移動到一個單獨的線程中,在該線程中它可以連續運行。 然后,onMessage函數仍可以將到達的消息存儲在數據庫中。
然后,您可以直接從數據庫中呈現結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.