Bird
0
0

Given this code snippet, what will be printed when the message 'Hello everyone' is published to the chat channel?

medium📝 component behavior Q13 of 15
Django - Celery and Background Tasks
Given this code snippet, what will be printed when the message 'Hello everyone' is published to the chat channel?
import redis

r = redis.Redis()

pubsub = r.pubsub()
pubsub.subscribe('chat')

for message in pubsub.listen():
    if message['type'] == 'message':
        print(f"Received: {message['data'].decode()}")
        break
AReceived: Hello everyone
BReceived: message
CReceived: chat
DNo output, code will error
Step-by-Step Solution
Solution:
  1. Step 1: Understand the subscription and listening

    The code subscribes to 'chat' channel and listens for messages.
  2. Step 2: Decode and print the message data

    When a message is received, it decodes the bytes and prints with prefix 'Received:'.
  3. Final Answer:

    Received: Hello everyone -> Option A
  4. Quick Check:

    Message data decoded and printed [OK]
Quick Trick: Listen loop prints decoded message data on 'message' type [OK]
Common Mistakes:
MISTAKES
  • Printing message type instead of data
  • Not decoding bytes to string
  • Assuming code errors without message

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes