📖 Scenario: You are building a simple Flask web app that uses Redis as a message broker to send and receive messages asynchronously.This is useful in real-world apps where you want to decouple parts of your system, like sending notifications or processing tasks in the background.
🎯 Goal: Build a Flask app that publishes messages to a Redis channel and subscribes to that channel to receive messages.You will create the Redis connection, configure the channel name, publish messages, and subscribe to messages using Redis Pub/Sub.
📋 What You'll Learn
Use the redis Python package to connect to Redis
Create a Redis client instance
Define a channel name as a configuration variable
Publish messages to the Redis channel
Subscribe and listen to messages from the Redis channel
💡 Why This Matters
🌍 Real World
Redis is often used as a fast message broker to enable communication between different parts of an application or between different services.
💼 Career
Understanding how to use Redis Pub/Sub with Flask is useful for backend developers building scalable, decoupled web applications and microservices.
Progress0 / 4 steps
1
Create Redis client connection
Import the redis package and create a Redis client instance called redis_client connecting to localhost on the default port.
Flask
Hint
Use redis.Redis() with host='localhost', port=6379, and db=0.
2
Define Redis channel name
Create a variable called channel_name and set it to the string 'flask_channel' to use as the Redis Pub/Sub channel.
Flask
Hint
Just assign the string 'flask_channel' to channel_name.
3
Publish a message to the Redis channel
Use the redis_client.publish() method to send the message 'Hello from Flask!' to the channel stored in channel_name.
Flask
Hint
Call redis_client.publish(channel_name, 'Hello from Flask!') to send the message.
4
Subscribe and listen to messages from the Redis channel
Create a PubSub object from redis_client called pubsub. Use pubsub.subscribe(channel_name) to subscribe. Then write a for loop iterating over pubsub.listen() to print messages when message['type'] == 'message'.
Flask
Hint
Use redis_client.pubsub() to create pubsub, subscribe with pubsub.subscribe(channel_name), then loop over pubsub.listen() checking message['type'] == 'message'.
Practice
(1/5)
1. What is the main role of Redis when used as a message broker in a Flask application?
easy
A. To serve static files like images and CSS
B. To store user passwords securely
C. To send and receive messages between different parts of the app
D. To handle HTTP requests directly
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 C
Quick Check:
Redis message broker = send/receive messages [OK]
Hint: Redis in Flask is for messaging, not storage or HTTP [OK]
Common Mistakes:
Confusing Redis with a database for user data
Thinking Redis serves static files
Assuming Redis handles HTTP requests
2. Which of the following is the correct way to publish a message to a Redis channel in Flask?
easy
A. redis_client.post('channel', 'message')
B. redis_client.send('channel', 'message')
C. redis_client.push('channel', 'message')
D. redis_client.publish('channel', 'message')
Solution
Step 1: Recall Redis publish method
Redis uses the method publish to send messages to a channel.
Step 2: Check method names
Only publish is the correct Redis command; others like send, push, or post are incorrect.
Final Answer:
redis_client.publish('channel', 'message') -> Option D
Quick Check:
Publish method = publish() [OK]
Hint: Use publish() to send messages in Redis [OK]
Common Mistakes:
Using send() instead of publish()
Confusing push() with publish()
Trying to use post() which is not a Redis method
3. Given the following Flask code snippet using Redis, what will be printed when a message is published to 'test_channel'?
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
medium
A. The published message content decoded as a string
B. The string 'test_channel'
C. The message type 'subscribe'
D. An error because decode() is not valid here
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 A
Quick Check:
Message data decoded = printed string [OK]
Hint: listen() yields messages; decode bytes to string before print [OK]
Common Mistakes:
Printing channel name instead of message data
Confusing message type 'subscribe' with 'message'
Forgetting to decode bytes to string
4. What is the main issue with this Flask Redis subscriber code snippet?
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.
medium
A. The listen() loop blocks the main thread, freezing the app
B. The decode() method is called on a string, causing an error
C. The subscribe() method is missing required parameters
D. Redis client is not connected to the server
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 A
Quick Check:
Blocking listen() = app freeze [OK]
Hint: listen() blocks; run it in background thread [OK]
Common Mistakes:
Thinking decode() causes error here
Believing subscribe() needs extra parameters
Assuming Redis connection is missing without error
5. You want to listen for Redis messages in a Flask app without freezing it. Which approach correctly solves this problem?
hard
A. Call pubsub.listen() directly in the main Flask route handler
B. Run the Redis pubsub.listen() loop inside a background thread
C. Use Redis publish() inside the listen() loop
D. Subscribe to Redis channels without calling listen()
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 B
Quick Check:
Background thread for listen() = no freeze [OK]
Hint: Use background thread to avoid blocking Flask [OK]
Common Mistakes:
Running listen() in main route causing freeze
Misusing publish() inside listen() loop
Subscribing without listen() so no messages received
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.