MQTT messages not received when Flask client is run behind uWSGI

自闭症网瘾萝莉.ら 提交于 2021-02-10 14:36:49

问题


I have a Flask application that subscribes to MQTT topics through a mosquitto broker (v 1.6.4). When run directly (using Flask's own server), the client connects, subscribes and receives messages. When the app is served by a uWSGI server (v 2.0.17), the client connects, subscribes but does not receive messages.

The logs from the client for the two scenarios are as follows. Only in the first scenario is the message received.

When run using Flask's own server:

python project.py

Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'full-client-54'

Received CONNACK (0, 0)

Sending SUBSCRIBE (d0, m1) [(b'/topics/drone/battery', 0)]

Received SUBACK

Received PUBLISH (d0, q0, r0, m0), '/topics/drone/battery', ... (76 bytes)

When run using uWSGI:

uwsgi --socket 0.0.0.0:8080 --protocol=http -w project:app -H env --workers 1

Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'full-client-54'

Received CONNACK (0, 0)

Sending SUBSCRIBE (d0, m1) [(b'/topics/drone/battery', 0)]

Received SUBACK

The client code is as follows:

import paho.mqtt.client as mqtt
import flask
import json


app = flask.Flask(__name__)


def  on_connect(client, userdata, flags, rc):
   client.subscribe(BATTERY_TOPIC)


def on_message(client, userdata, msg):
   data = json.loads(msg.payload)

   # custom code


def on_log(client, userdata, level, buf):
        print(buf)


client = mqtt.Client('full-client-54')
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username=USER_NAME, password=PWD)
client.on_log=on_log


try:
   client.connect(BROKER_IP)
   client.loop_start()
except Exception: 
   print('Exception when connecting to mqtt broker')

Does anyone know why, with this setup, messages are not properly received when the MQTT client is being served by uWSGI?


回答1:


The same with you. the solution is to change uwsgi to gunicorn, it works fine.



来源:https://stackoverflow.com/questions/57553334/mqtt-messages-not-received-when-flask-client-is-run-behind-uwsgi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!