Flask is a lightweight web application framework written in Python, which is called a "micro-framework" because it uses a simple core and adds other functions with extensions, such as: ORM, form validation tools, file uploads, various Open authentication technologies, etc.
MQTT is a lightweight IoT message transmission protocol based on the publish/subscribe model, which can provide real-time and reliable message services for networked devices with very little code and bandwidth. It is widely used in the Internet of Things, mobile Internet, smart hardware, Internet of vehicles, electric power and other industries.
This article mainly introduces how to realize the connection, subscription, unsubscribe, sending and receiving of messages and other functions between the MQTT client and the MQTT server in the Flask project.
We will use the Flask-MQTT client library, which is a Flask extension that can be seen as a paho-mqtt decorator to simplify MQTT integration in Flask applications.
Project initialization
This project uses Python 3.8 for development and testing. Readers can use the following commands to confirm the Python version.
$ python3 --version
Python 3.8.2
Install the Flask-MQTT library with Pip
pip3 install flask-mqtt
Flask-MQTT usage
This article will use the free public MQTT server provided by EMQ, which is based on the MQTT cloud service - EMQX Cloud. The server access information is as follows:
- Broker:
broker.emqx.io
- TCP Port:
1883
- Websocket Port:
8083
Import Flask-MQTT
Import the Flask library and the Flask-MQTT extension, and create a Flask application
from flask import Flask, request, jsonify
from flask_mqtt import Mqtt
app = Flask(__name__)
Configure the Flask-MQTT extension
app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = '' # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_PASSWORD'] = '' # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_KEEPALIVE'] = 5 # 设置心跳时间,单位为秒
app.config['MQTT_TLS_ENABLED'] = False # 如果你的服务器支持 TLS,请设置为 True
topic = '/flask/mqtt'
mqtt_client = Mqtt(app)
For complete configuration items, please refer to the Flask-MQTT configuration documentation.
Write the connection callback function
The success or failure of the MQTT connection can be handled in this callback function. This example will subscribe to the topic /flask/mqtt
after the connection is successful.
@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
if rc == 0:
print('Connected successfully')
mqtt_client.subscribe(topic) # 订阅主题
else:
print('Bad connection. Code:', rc)
Write a message callback function
This function will print /flask/mqtt
the message received by the topic.
@mqtt_client.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print('Received message on topic: {topic} with payload: {payload}'.format(**data))
Create a publish message interface
We create a simple POST interface to implement MQTT message publishing.
In practical applications, this interface may require some more complex business logic processing.
@app.route('/publish', methods=['POST'])
def publish_message():
request_data = request.get_json()
publish_result = mqtt_client.publish(request_data['topic'], request_data['msg'])
return jsonify({'code': publish_result[0]})
Run the Flask app
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
When the Flask app starts, the MQTT client will connect to the server and subscribe to the topic /flask/mqtt
.
test
Next, we use the MQTT client - MQTT X for connection, subscription, and publishing tests.
Test message reception
Create a link in MQTT X and connect to the server.
Publish message
Hello from MQTT X
/flask/mqtt
in MQTT X.The messages sent by MQTT X will be visible in the Flask run window.
Test message publishing interface
Subscribe to
/flask/mqtt
topic in MQTT X.Using Postman call
/publish
interface: send messageHello from Flask
to/flask/mqtt
topic.In MQTT X, you will be able to see the message sent by Flask.
full code
from flask import Flask, request, jsonify
from flask_mqtt import Mqtt
app = Flask(__name__)
app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = '' # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_PASSWORD'] = '' # 当你需要验证用户名和密码时,请设置该项
app.config['MQTT_KEEPALIVE'] = 5 # 设置心跳时间,单位为秒
app.config['MQTT_TLS_ENABLED'] = False # 如果你的服务器支持 TLS,请设置为 True
topic = '/flask/mqtt'
mqtt_client = Mqtt(app)
@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
if rc == 0:
print('Connected successfully')
mqtt_client.subscribe(topic)
else:
print('Bad connection. Code:', rc)
@mqtt_client.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print('Received message on topic: {topic} with payload: {payload}'.format(**data))
@app.route('/publish', methods=['POST'])
def publish_message():
request_data = request.get_json()
publish_result = mqtt_client.publish(request_data['topic'], request_data['msg'])
return jsonify({'code': publish_result[0]})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
Precautions
Flask-MQTT is currently not suitable for using multiple worker instances, if you need to use a WSGI server like gevent or gunicorn , make sure there is only one worker instance.
Summarize
So far, we have completed a simple MQTT client using Flask-MQTT, and can subscribe and publish messages in the Flask application.
Copyright statement: This article is original by EMQ, please indicate the source when reprinting.
Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-flask
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。