Refactor button handling in index.html and app.py

This commit is contained in:
ishak jmilou.ishak
2024-10-24 12:14:52 +02:00
parent 4f3bb0b009
commit 5fe14a2f8f
3 changed files with 60 additions and 26 deletions

View File

@@ -1,4 +1,4 @@
from flask import Flask, request, render_template
from flask import Flask, request, render_template, jsonify
import paho.mqtt.client as mqtt
app = Flask(__name__)
@@ -10,15 +10,18 @@ mqtt_client.username_pw_set("ishak", "kobuki")
mqtt_client.connect("localhost", 1883, 60)
mqtt_client.loop_start()
@app.route('/', methods=['GET', 'POST'])
@app.route('/')
def index():
message = ''
if request.method == 'POST':
direction = request.form['direction']
result = mqtt_client.publish("home/commands", direction)
if result.rc == mqtt.MQTT_ERR_SUCCESS:
message = "Bericht succesvol gepubliceerd"
return render_template('index.html', message=message)
return render_template('index.html')
@app.route('/move', methods=['POST'])
def move():
direction = request.form['direction']
result = mqtt_client.publish("home/commands", direction)
if result.rc == mqtt.MQTT_ERR_SUCCESS:
return jsonify({"message": "Bericht succesvol gepubliceerd"}), 200
else:
return jsonify({"message": "Fout bij het publiceren van bericht"}), 500
if __name__ == '__main__':
app.run(debug=True)
app.run(debug=True)