플라스크에 mqtt를 구현하는 방법에 관한 질문을하고 싶습니다. 필자는 특정 페이지로 이동하면 메시지를 수신하고 데이터베이스에 저장 한 다음 해당 페이지의 테이블에 메시지를 출력하는 코드를 작성했습니다.플라스크에 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'페이지로 이동하면 다음 오류가 표시됩니다.
'오류'나는 이것이 내가 충분히 잘 이해할 수있는 예 또는 자습서를 발견하지 않았기 때문에 나는 'views.py'에서 스크립트를 작성하는 방식에 문제가 있어야합니다 생각
UndefinedError: 'message' is undefined
플라스크에 mqtt을 구현하십시오. 그래서 나는 그것을 스스로 구현하려고 노력했다.
본인의 의견을 듣고 자합니다.
미리 감사드립니다.
모델이 깨졌습니다. 클라이언트가 페이지를 렌더링하는 데 걸린 시간 동안 만 연결되어 있으면 메시지를받지 못할 것입니다. – hardillb
어떤 줄이 예외를 제기합니까? – dirn
@dim 'views.py'의 줄이 'message = ...'라는 오류로 인해 – Ling