0
0
Djangoframework~30 mins

Redis as message broker in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Redis as message broker
📖 Scenario: You are building a simple Django app that uses Redis as a message broker to send and receive messages between parts of your app.This is like a post office where one part sends letters (messages) and another part picks them up.
🎯 Goal: Create a Django setup that connects to Redis, sends a message to a Redis channel, and listens for messages from that channel.
📋 What You'll Learn
Create a Redis connection in Django
Set a Redis channel name as a configuration variable
Write a function to publish a message to the Redis channel
Write a function to subscribe and listen to messages from the Redis channel
💡 Why This Matters
🌍 Real World
Redis is often used as a fast message broker to connect different parts of web apps or microservices.
💼 Career
Understanding Redis messaging helps in building scalable, real-time Django applications and working with modern backend architectures.
Progress0 / 4 steps
1
Setup Redis connection
Create a Redis connection called redis_client using redis.Redis() with host='localhost' and port=6379.
Django
Need a hint?

Use redis.Redis(host='localhost', port=6379) to connect to Redis server.

2
Set Redis channel name
Create a variable called CHANNEL_NAME and set it to the string 'my_channel'.
Django
Need a hint?

Just assign the string 'my_channel' to CHANNEL_NAME.

3
Publish message function
Write a function called publish_message that takes a message parameter and publishes it to CHANNEL_NAME using redis_client.publish().
Django
Need a hint?

Use redis_client.publish(CHANNEL_NAME, message) inside the function.

4
Subscribe and listen function
Write a function called subscribe_and_listen that subscribes to CHANNEL_NAME using redis_client.pubsub(), listens for messages in a loop, and prints the message data when received.
Django
Need a hint?

Use redis_client.pubsub() to create a subscriber, subscribe to CHANNEL_NAME, then loop over pubsub.listen() to get messages.