DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mistakes That Django Developers Make and How To Avoid Them
  • OPC-UA and MQTT: A Guide to Protocols, Python Implementations
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud
  • 5 Reasons To Choose Django in 2024

Trending

  • A Guide to Container Runtimes
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Use MQTT in The Django Project

How to Use MQTT in The Django Project

This article mainly introduces how to connect, subscribe, unsubscribe, and send and receive messages between MQTT clients and brokers in the Django project.

By 
Ming Zhao user avatar
Ming Zhao
·
Nov. 09, 22 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
7.9K Views

Join the DZone community and get the full member experience.

Join For Free

MQTT is a lightweight IoT messaging protocol based on publish/subscribe model, which can provide real-time reliable messaging services for connected devices with very little code and bandwidth. It is widely used in industries such as IoT, mobile Internet, smart hardware, Internet of vehicles, and power and energy.

Django is an open-source Web framework and one of the more popular Python Web frameworks. This article mainly introduces how to connect, subscribe, unsubscribe, and send and receive messages between MQTT clients and MQTT brokers in the Django project.

We will write a simple MQTT client using the paho-MQTT client library. paho-mqtt is a widely used MQTT client library in Python that provides client support for MQTT 5.0, 3.1.1, and 3.1 on Python 2.7 and 3.x.

Project Initialization

This project uses Python 3.8 for development testing, and the reader can confirm the version of Python with the following command.

 
$ python3 --version
Python 3.8.2

Install Django and paho-mqtt using Pip.

 
pip3 install django
pip3 install paho-mqtt

Create a Django project.

 
django-admin startproject mqtt-test

The directory structure after creation is as follows.

 
├── manage.py
└── mqtt_test
  ├── __init__.py
  ├── asgi.py
  ├── settings.py
  ├── urls.py
  ├── views.py
  └── wsgi.py

Using Paho-MQTT

This article will use free public MQTT Broker provided by EMQ. The service is created based on MQTT Cloud service - EMQX Cloud. The server access information is as follows:

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

Import Paho-MQTT

 
import paho.mqtt.client as mqtt

Writing Connection Callback

Successful or failed MQTT connections can be handled in this callback function, and this example will subscribe to the django/mqtt topic after a successful connection.

 
def on_connect(mqtt_client, userdata, flags, rc):
   if rc == 0:
       print('Connected successfully')
       mqtt_client.subscribe('django/mqtt')
   else:
       print('Bad connection. Code:', rc)

Writing Message Callback

This function will print the messages received by the django/mqtt topic.

 
def on_message(mqtt_client, userdata, msg):
   print(f'Received message on topic: {msg.topic} with payload: {msg.payload}')


Adding Django Configuration Items

Add configuration items for the MQTT broker in settings.py. Readers who have questions about the following configuration items and MQTT-related concepts mentioned in this article can check out the blog The Easiest Guide to Getting Started with MQTT.

This example uses anonymous authentication, so the username and password are set to empty.

 
MQTT_SERVER = 'broker.emqx.io'
MQTT_PORT = 1883
MQTT_KEEPALIVE = 60
MQTT_USER = ''
MQTT_PASSWORD = ''


Configuring the MQTT Client

 
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)
client.connect(
    host=settings.MQTT_SERVER,
    port=settings.MQTT_PORT,
    keepalive=settings.MQTT_KEEPALIVE
)

Creating a Message Publishing API

We create a simple POST API to implement MQTT message publishing.

In actual applications, the API code may require more complex business logic processing.

Add the following code in views.py.

 
import json
from django.http import JsonResponse
from mqtt_test.mqtt import client as mqtt_client


def publish_message(request):
    request_data = json.loads(request.body)
    rc, mid = mqtt_client.publish(request_data['topic'], request_data['msg'])
    return JsonResponse({'code': rc})

Add the following code in urls.py.

 
from django.urls import path
from . import views

urlpatterns = [
    path('publish', views.publish_message, name='publish'),
]

Start the MQTT Client

Add the following code in __init__.py.

 
from . import mqtt
mqtt.client.loop_start()

At this point, we have finished writing all the code, and the full code can be found on GitHub.

Finally, execute the following command to run the Django project.

 
python3 manage.py runserver

When the Django application starts, the MQTT client will connect to the MQTT Broker and subscribe to the topic django/mqtt.

Testing

Next, we will use an open-source cross-platform MQTT client - MQTT X, to test connection, subscription, and publishing.

Test Message Receiving

  1. Create an MQTT connection in MQTT X, enter the connection name, leave the other parameters as default, and click the Connect button in the upper right corner to connect to the broker.

    Create an MQTT connection in MQTT X,

  2. Publish the message Hello from MQTT X to the django/mqtt topic in the message publishing box at the bottom of MQTT X.

    the message publishing box at the bottom of MQTT X

  3. The messages sent by MQTT X will be visible in the Django runtime window.

    The messages sent by MQTT X will be visible in the Django runtime window.

Test Message Publishing API

  1. Subscribe to the django/mqtt topic in MQTT X.

    Test Message Publishing API

  2. Use Postman to call /publish API: publish the message Hello from Django to the django/mqtt topic.


  3. You will see the messages sent by Django in MQTT X.

    messages sent by Django in MQTT X.

Summary

At this point, we have completed the development of the MQTT client using paho-mqtt, enabling communication using MQTT in Django applications. In practice, we can extend the MQTT client to achieve more complex business logic based on business requirements.


MQTT Django (web framework)

Published at DZone with permission of Ming Zhao. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mistakes That Django Developers Make and How To Avoid Them
  • OPC-UA and MQTT: A Guide to Protocols, Python Implementations
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud
  • 5 Reasons To Choose Django in 2024

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!