I have a requirement where will have a POST api call ,read the json data from this and publish the messages to this topic "/home/floor_1/room" before publishing need to connect to the broker also and then return a success response . Project structure:
│ app.py
│ config.py
│ Dockerfile
│ requirement.txt
│
├───app_services
│ │ __init__.py
│ │
│ ├───controller
│ │ │ send_down_link.py
│ │ │ __init__.py
│ │
│ ├───models
│ │ │ __init__.py
│ │ │
│ │ ├───database
│ │ │ │ device.py
In app.py
from app_services import app
if __name__ == '__main__':
app.run(host=app.config['HOST'], port=app.config['PORT'], debug=app.config['DEBUG'])
in app_service/ init .py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api
from flask_mqtt import Mqtt
from app_service.controller.send_down_link import SendDownlink
app = Flask(__name__)
db = SQLAlchemy(app)
mqtt = Mqtt(app)
api = Api(app)
api.add_resource(SendDownlink, "/api/t1/device/")
In controller/send_down_link.py:
class SendDownlink(Resource):
def post(self):
input_data = request.get_json()
message = input_data['message']
I want to publish this message to "/home/floor_1/room" topic . So i just want accommodate mqtt code in this 'post' method. Dont know how to work around it . Any suggestion ?
Given your stated goal is to just publish a message then the simplest way is to use the shortcut method provided by the Paho library that will handle all the connection and publication in a single call.
https://pypi.org/project/paho-mqtt/#publish-single-example
eg
import paho.mqtt.publish as publish
publish.single("home/floor_1/room", "payload", hostname="mqtt.eclipse.org")
ps Topics really shouldn't start with a leading /
, it adds an unneeded null
to the start of the topic tree and breaks things like Shared Subscriptions when you try and scale things later.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.