Redis as a message broker helps different parts of your app talk to each other quickly and reliably.
Redis as message broker in Django
import redis r = redis.Redis(host='localhost', port=6379, db=0) r.publish('channel_name', 'message') pubsub = r.pubsub() pubsub.subscribe('channel_name') for message in pubsub.listen(): print(message)
Use publish to send messages to a channel.
Use subscribe to listen for messages on a channel.
r.publish('chat', 'Hello everyone!')
pubsub.subscribe('chat') for msg in pubsub.listen(): print(msg)
This Django-friendly Python script uses Redis to send and receive messages on the 'notifications' channel. It starts a listener in the background that prints any received messages. Then it sends three notifications one by one with a pause.
import redis import threading import time r = redis.Redis(host='localhost', port=6379, db=0) # Function to listen for messages def listen(): pubsub = r.pubsub() pubsub.subscribe('notifications') for message in pubsub.listen(): if message['type'] == 'message': print(f"Received: {message['data'].decode()}") # Start listener in a separate thread listener_thread = threading.Thread(target=listen, daemon=True) listener_thread.start() # Simulate sending messages for i in range(3): msg = f"Notification {i+1}" r.publish('notifications', msg) print(f"Sent: {msg}") time.sleep(1)
Make sure Redis server is running on your machine before running the code.
Use decoding like message['data'].decode() to convert bytes to string.
Running the listener in a separate thread helps your app keep working while waiting for messages.
Redis can send messages between parts of your Django app fast and easily.
Use publish to send and subscribe to receive messages.
Running listeners in background threads keeps your app responsive.