MQTT framework is a library that provides an opinionated structure for setting up message handlers and publishers for MQTT brokers. It is built on top of the paho-mqtt library.
- Python 3.8+
We highly recommend and only officially support the latest patch release of each Python series.
Install using pip.
pip install python-mqtt-framework
This is how you write the topic handlers:
from mqtt_framework import TopicHandler
from rest_framework import serializers
from pydantic import BaseModel
class SimpleTestModel(BaseModel):
testing: str
class SimpleTestSerializer(serializers.Serializer):
testing = serializers.CharField()
def create(self, validated_data):
print('test_message', validated_data)
return validated_data
class SerializerTopicHandler(TopicHandler):
topic = 'test/topic'
serializer_class = SimpleTestSerializer
qos = 1
# Calls the serializer's "save" method
class PydanticTopicHandler(TopicHandler):
topic = 'another/topic'
pydantic_model = SimpleTestModel
qos = 0
def handle(self):
pydantic_instance = self.get_validated_payload()
# Do something with the pydantic_instanceThere's no need to register the topic handlers, the framework will automatically discover them as long as they are imported.
Add 'mqtt_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [
# ...
'mqtt_framework',
]Then you add the MQTT_FRAMEWORK setting:
MQTT_FRAMEWORK = {
'BROKER_URL': 'mqtt://<user>:<password>@<host>:<port>',
'TOPIC_HANDLERS': 'your_app.topic_handlers',
'KEEPALIVE': 60,
}To run the MQTT listener, you can use the runmqtt management command:
python manage.py runmqtt