Python Flask server with MQTT subscription Python Flask server with MQTT subscription flask flask

Python Flask server with MQTT subscription


You need to pass the details of the broker you want to connect to in the connect() function

e.g.

...client.on_message = on_messageclient.connect('broker.example.com')client.subscribe(topic)...

EDIT: you also need to start the network loop. Given this is flask app you will want to start the loop in the background so use the loop_start function.

...client.connect('broker.example.com')client.loop_start()...

You should also move the subscribe and publish calls to the on_connect callback as they need to wait for the connection to have been established before being run.

EDIT2: adding full working code:

from flask import Flaskimport paho.mqtt.client as mqttapp = Flask(__name__)topic = 'foo'topic2 = 'bar'port = 5000def on_connect(client, userdata, rc):    client.subscribe(topic)    client.publish(topic2, "STARTING SERVER")    client.publish(topic2, "CONNECTED")def on_message(client, userdata, msg):    client.publish(topic2, "MESSAGE")@app.route('/')def hello_world():    return 'Hello World! I am running on port ' + str(port)if __name__ == '__main__':    client = mqtt.Client()    #client.username_pw_set(username, password)    client.on_connect = on_connect    client.on_message = on_message    client.connect('localhost')    client.loop_start()    app.run(host='0.0.0.0', port=port)


You can use also Flask-MQTT:

https://flask-mqtt.readthedocs.io/en/latest/usage.html

There is even functional example how to implement MQTT-SocketIO bridge, which is just what I was looking for. This worked out-of-the-box:

https://flask-mqtt.readthedocs.io/en/latest/usage.html#interact-with-socketio