Forums

Flask MQTT works in console but doesn't in web app

I tried to run flask-mqtt on my free acount it sound it can't be done on free accounts so i upgraded to hacker and now it still doesn't work but when import the client_mqtt from my app in console it works well but in my web app it doesn't please help, thank you!.

app1.config['MQTT_BROKER_URL'] = 'mybroker'

app1.config['MQTT_BROKER_PORT'] = 1883

app1.config['MQTT_USERNAME'] = ' '

app1.config['MQTT_PASSWORD'] = ' '

app1.config['MQTT_KEEPALIVE'] = 5

app1.config['MQTT_TLS_ENABLED'] = False

mqtt_client = Mqtt(app1)

import sys as syss

@mqtt_client.on_connect()

def handle_connect(client,userdata,flags,rc):

    if rc == 0:
        print('Connected successfully', file = syss.stderr)
        mqtt_client.subscribe('esp/copra')
    else:
        print('Bad connection. Code:', rc , file=syss.stderr)

testmqtt="a"

@mqtt_client.on_message()

def handle_mqtt_message(client,userdata,message):

    payload = message.payload.decode()

    print("payload is " + payload)


@app1.route("/testmqtt")

def testmqtt():

    print("test mqtt here")

    mqtt_client.publish('esp/copra',"pythonanywhere")

    return{"mqtt": "mqtt"}

if __name__ == "__main__":

    #app.config['SESSION_TYPE'] = 'filesystem'

    mqtt_client.init_app(app1)

    app1.run()

[edit by admin: formatting]

and I also tried it without adding mqtt_client.init_app(app1) in the main, same problem

.

I don't think you will be able to receive MQTT messages inside Flask code. When we start up your website, there will be multiple instances running in different processes so that you can handle multiple requests in parallel. So you'll need to receive messages in a separate single process (perhaps using an always-on task) and make the data in those messages available to the Flask code in some other fashion -- perhaps via a database.

[edit: noticed the answer to my original question in the code, so changed response]

But how can I publish data to broker on Post route and subscribe to new topic on some post requests?

The subscribing could be a bit tricky; you'd need to pass that from the website code to the always-on task somehow. Perhaps store it in a MySQL table and check that periodically from the task?

The publishing, I think, should work from inside the website code -- it's only the receiving of messages that I wouldn't expect to work.

I can publish messages if I used in the server bash terminal. Inside the Flask app. #!python

flask shell from paho import mqtt > mqtt.publish.single("mythread","mydata",hostname="test.mosquitto.org", port=1883)

The code in my routes.py

from paho import mqtt ... ... @main.route('/publish', methods=['POST']) def publish(): mqtt.publish.single("mythread","mydata",hostname="test.mosquitto.org", port=1883)

If you run web app in the bash console on PythonAnywhere it would not be visible to the outside world.