Redis as a message broker helps different parts of your app talk to each other by sending messages quickly and simply.
Redis as message broker in Flask
import redis r = redis.Redis(host='localhost', port=6379, db=0) r.publish('channel_name', 'your 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 and listen to receive messages from a channel.
r.publish('news', 'Hello subscribers!')
pubsub = r.pubsub() pubsub.subscribe('news') for msg in pubsub.listen(): print(msg)
This Flask app lets you send messages to a Redis channel called 'chat' via a POST request to '/send'. A background thread listens and prints messages received on that channel.
from flask import Flask, request import redis import threading app = Flask(__name__) r = redis.Redis(host='localhost', port=6379, db=0) # Background thread to listen for messages def listen_messages(): pubsub = r.pubsub() pubsub.subscribe('chat') for message in pubsub.listen(): if message['type'] == 'message': print(f"Received: {message['data'].decode()}") listener_thread = threading.Thread(target=listen_messages, daemon=True) listener_thread.start() @app.route('/send', methods=['POST']) def send_message(): msg = request.form.get('message', '') if msg: r.publish('chat', msg) return 'Message sent!' return 'No message provided', 400 if __name__ == '__main__': app.run(debug=True)
Make sure Redis server is running before starting your Flask app.
Use background threads or separate processes to listen for messages without blocking your app.
Decode message data from bytes to string when receiving messages.
Redis can send and receive messages between parts of your Flask app.
Use publish to send and subscribe with listen to receive.
Background threads help listen for messages without stopping your app.
Practice
Solution
Step 1: Understand Redis as a message broker
Redis acts as a middleman to send messages between parts of an app, enabling communication.Step 2: Identify Redis's role in Flask
It is not used for storing passwords, serving files, or handling HTTP requests directly.Final Answer:
To send and receive messages between different parts of the app -> Option CQuick Check:
Redis message broker = send/receive messages [OK]
- Confusing Redis with a database for user data
- Thinking Redis serves static files
- Assuming Redis handles HTTP requests
Solution
Step 1: Recall Redis publish method
Redis uses the methodpublishto send messages to a channel.Step 2: Check method names
Onlypublishis the correct Redis command; others likesend,push, orpostare incorrect.Final Answer:
redis_client.publish('channel', 'message') -> Option DQuick Check:
Publish method = publish() [OK]
- Using send() instead of publish()
- Confusing push() with publish()
- Trying to use post() which is not a Redis method
import redis
r = redis.Redis()
pubsub = r.pubsub()
pubsub.subscribe('test_channel')
for message in pubsub.listen():
if message['type'] == 'message':
print(message['data'].decode())
break
Solution
Step 1: Understand pubsub.listen() behavior
The loop listens for messages on 'test_channel'. When a message of type 'message' arrives, it prints the decoded data.Step 2: Decode message data
The message data is bytes, so decode() converts it to a string, which is printed.Final Answer:
The published message content decoded as a string -> Option AQuick Check:
Message data decoded = printed string [OK]
- Printing channel name instead of message data
- Confusing message type 'subscribe' with 'message'
- Forgetting to decode bytes to string
import redis
r = redis.Redis()
pubsub = r.pubsub()
pubsub.subscribe('channel')
for message in pubsub.listen():
if message['type'] == 'message':
print(message['data'].decode())
It causes the Flask app to freeze and not respond.Solution
Step 1: Analyze listen() behavior
The listen() method blocks execution, waiting for messages indefinitely.Step 2: Understand Flask app impact
Running listen() in the main thread stops Flask from handling other requests, freezing the app.Final Answer:
The listen() loop blocks the main thread, freezing the app -> Option AQuick Check:
Blocking listen() = app freeze [OK]
- Thinking decode() causes error here
- Believing subscribe() needs extra parameters
- Assuming Redis connection is missing without error
Solution
Step 1: Identify blocking issue with listen()
Calling listen() in the main thread blocks Flask, freezing the app.Step 2: Use background thread for listening
Running listen() in a separate thread allows Flask to stay responsive while listening for messages.Final Answer:
Run the Redis pubsub.listen() loop inside a background thread -> Option BQuick Check:
Background thread for listen() = no freeze [OK]
- Running listen() in main route causing freeze
- Misusing publish() inside listen() loop
- Subscribing without listen() so no messages received
Ready to prove it?
Pass the test and this pattern moves unknown
