成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

How to use MQTT in Flask

原創 精選
Techplur
This article mainly introduces how to use MQTT in the Flask project, and implement the connection, subscription, messaging, unsubscribing and other functions between the ??MQTT client?? and ??MQTT bro

??Flask?? is a lightweight Web application framework written with Python, which is called "micro-framework" because it uses a simple core for extension of other features, such as: ORM, form validation tools, file upload, various open authentication techniques, etc.

??MQTT?? is a lightweight Internet of Things (IoT) message transmission protocol based on publish/subscribe mode. It can provide a real-time and reliable message service for networked devices with very less code and smaller bandwidth. It is widely used in IoT, mobile Internet, intelligent hardware, IoV, power and energy industries, etc.

This article mainly introduces how to use MQTT in the Flask project, and implement the connection, subscription, messaging, unsubscribing and other functions between the ??MQTT client??? and ??MQTT broker??.

We will use the ??Flask-MQTT??? client library, which is a Flask extension and can be regarded as a decorator of ??paho-mqtt?? to simplify the MQTT integration in Flask applications.


Project Initialization

This project is developed and tested with Python 3.8, and users may use the following commands to verify the version of Python.

$ python3 --version
Python 3.8.2

Use Pip to install the Flask-MQTT library.

pip3 install flask-mqtt

Use Flask-MQTT

We will adopt the ??Free public MQTT broker??? provided by EMQ, which is created on the basis of ??MQTT cloud service - EMQX Cloud??. The following is the server access information:

  • Broker:??broker.emqx.io??
  • TCP Port: 1883
  • Websocket Port: 8083


Import Flask-MQTT

Import the Flask library and Flask-MQTT extension, and create the Flask application.

from flask import Flask, request, jsonify
from flask_mqtt import Mqtt

app = Flask(__name__)

Configure Flask-MQTT extension

app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = '' # Set this item when you need to verify username and password
app.config['MQTT_PASSWORD'] = '' # Set this item when you need to verify username and password
app.config['MQTT_KEEPALIVE'] = 5 # Set KeepAlive time in seconds
app.config['MQTT_TLS_ENABLED'] = False # If your server supports TLS, set it True
topic = '/flask/mqtt'

mqtt_client = Mqtt(app)

For complete configuration items, please refer to ??Flask-MQTT configuration document??.


Write connect callback function

We can handle successful or failed MQTT connections in this callback function, and this example will subscribe to the ??/flask/mqtt?? topic after a successful connection.

@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
if rc == 0:
print('Connected successfully')
mqtt_client.subscribe(topic) # subscribe topic
else:
print('Bad connection. Code:', rc)

Write message callback function

This function will print the messages received by the ??/flask/mqtt?? 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 message publish API

We create a simple POST API to publish the MQTT messages.

In practical case, the API may need some more complicated 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 Flask application

When the Flask application is started, the MQTT client will connect to the server and subscribe to the topic ??/flask/mqtt??.

if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)

Test

Now, we use the ??MQTT client - MQTT X?? to connect, subscribe, and publish tests.


Receive message

  1. Create a connection in MQTT X and connect to the MQTT server.

  1. Publish ??Hello from MQTT X??? to the ??/flask/mqtt?? topic in MQTT X.

  1. We will see the message sent by MQTT X in the Flask running window.
    Flask receive MQTT message


Publish message

  1. Subscribe to the ??/flask/mqtt?? topic in MQTT X.

MQTT X subscribe

  1. Use Postman to call the ??/publish??? API: Send the message ??Hello from Flask??? to the ??/flask/mqtt??? topic.
    Postman test
  2. We can see the message sent from Flask in MQTT X.


Complete 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'] = '' # Set this item when you need to verify username and password
app.config['MQTT_PASSWORD'] = '' # Set this item when you need to verify username and password
app.config['MQTT_KEEPALIVE'] = 5 # Set KeepAlive time in seconds
app.config['MQTT_TLS_ENABLED'] = False # If your broker supports TLS, set it 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) # 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)

Limitations

Flask-MQTT is currently not suitable for the use with multiple worker instances. So if you use a WSGI server like gevent or gunicorn make sure you only have one worker instance.


Summary

So far, we have completed a simple MQTT client using Flask-MQTT and can subscribe and publish messages in the Flask application.

責任編輯:龐桂玉 來源: 51CTO
相關推薦

2016-11-08 10:24:37

FlaskPython插件

2022-08-30 21:47:03

MQTT ProtoOthers

2018-08-17 06:13:16

物聯網協議MQTTMQTT-SN

2022-09-26 11:30:40

MQTT協議客戶端協議

2023-08-25 09:17:38

2020-11-18 11:36:35

鴻蒙系統

2021-03-15 08:40:42

Vue組件函數

2016-08-29 17:28:53

JavascriptHtmlThis

2020-12-07 12:47:22

MQTT鴻蒙hi3861

2017-02-15 09:25:36

iOS開發MQTT

2020-11-17 08:59:28

MQTT

2020-07-04 10:41:32

MQTTSSE網絡協議

2021-08-19 07:25:02

數據庫Flask插件

2015-06-23 16:36:11

Web性能優化

2015-06-29 14:03:07

2015-06-03 10:14:20

2015-08-17 10:35:56

Web性能優化

2010-07-23 15:17:43

Perl use

2021-11-26 22:51:31

FlaskBlueprintsViews

2021-04-28 07:03:28

DjangoFlaskFastAPI
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产黄色一级片 | 精品久久久久久亚洲国产800 | 精品视频免费 | 欧美精品一区二区免费视频 | 99久久精品视频免费 | 一区二区三区免费在线观看 | 日韩视频精品在线 | 日韩一二区在线 | 亚洲欧美第一视频 | 久久综合影院 | 成人在线精品 | japanhdxxxx裸体| 国产综合精品一区二区三区 | 国产1区2区在线观看 | 欧美一级黄色片免费观看 | 中文字幕一页二页 | 成人免费大片黄在线播放 | 视频二区 | 成人激情视频免费在线观看 | 国产综合久久久久久鬼色 | 另类专区亚洲 | 污片在线观看 | 雨宫琴音一区二区在线 | 亚洲国产精品成人无久久精品 | 成年人网站免费 | 免费一看一级毛片 | a级在线 | 精品福利在线 | 欧美激情国产精品 | 最新国产精品视频 | 91久久| 很黄很污的网站 | 欧美激情精品久久久久久 | 成人天堂 | 97av在线| 欧美日韩亚洲一区 | 99亚洲精品视频 | 久久久国产一区二区三区四区小说 | 国产精品美女一区二区 | 国产中文字幕在线 | 成人国产精品久久 |