version flask proxy + htmx

This commit is contained in:
Clavier Paul 2022-05-10 15:02:41 +02:00
parent 37bad5a3ff
commit cc7eaef635
4 changed files with 62 additions and 1 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/venv/

42
main.py Normal file
View File

@ -0,0 +1,42 @@
from flask import Flask, render_template, request
from flask_mqtt import Mqtt
app = Flask(__name__)
app.config['MQTT_BROKER_URL'] = 'localhost'
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
mqtt = Mqtt(app)
DATA = []
@mqtt.on_connect()
def connect(client, userdata, flags, rc):
mqtt.subscribe('main')
@mqtt.on_message()
def message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload
)
DATA.append(data)
@app.route('/get')
def get():
if not DATA:
return ''
return '<ul>' + ''.join(
[f"<li>{data['topic']}: {data['payload']}" for data in DATA]
) + '</ul>'
@app.route('/send', methods=["POST"])
def send():
message = request.form.get('msg')
mqtt.publish('main', message)
return 'OK'
@app.route('/')
def home():
return render_template("index.html")
app.run()

View File

@ -1 +1,2 @@
paho-mqtt flask
flask-mqtt

17
templates/index.html Normal file
View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Client MQTT avec proxy flask</title>
<script src="https://unpkg.com/htmx.org@1.7.0" integrity="sha384-EzBXYPt0/T6gxNp0nuPtLkmRpmDBbjg6WmCUZRLXBBwYYmwAUxzlSGej0ARHX0Bo" crossorigin="anonymous" defer></script>
</head>
<body>
<p>Derniers messages:</p>
<dev hx-get="/get" hx-trigger="every 1s"></dev>
<p>Envoyer un message</p>
<form hx-post="/send" hx-swap="none">
<input id="msg" name="msg" type="text">
<button type="submit">OK</button>
</form>
</body>
</html>