Python consumer in Kafka - Commands & Configuration
pip install confluent-kafkapython kafka_consumer.py
If you remember nothing else from this pattern, remember: the Python consumer connects to Kafka, subscribes to topics, and continuously polls for new messages to process.
from confluent_kafka import Consumer, KafkaException config = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'my-group', 'auto.offset.reset': 'earliest' } consumer = Consumer(config) consumer.subscribe(['example-topic']) try: while True: msg = consumer.poll(1.0) # Wait up to 1 second for a message if msg is None: continue if msg.error(): raise KafkaException(msg.error()) print(f"Received message: {msg.value().decode('utf-8')}") consumer.commit(asynchronous=False) except KeyboardInterrupt: pass finally: consumer.close()
Practice
What is the main purpose of a Python Kafka consumer?
Solution
Step 1: Understand Kafka consumer role
A Kafka consumer reads data from Kafka topics to use in applications.Step 2: Differentiate from producer
Producers send messages, consumers read them. Monitoring and topic creation are separate tasks.Final Answer:
To read messages from Kafka topics and process them in Python -> Option CQuick Check:
Consumer = reads messages [OK]
- Confusing consumer with producer
- Thinking consumer creates topics
- Assuming consumer monitors server
Which of the following is the correct way to create a KafkaConsumer in Python to read from topic my_topic on localhost?
from kafka import KafkaConsumer consumer = KafkaConsumer(_____)
Solution
Step 1: Check KafkaConsumer parameters
KafkaConsumer expects topic name as string and bootstrap_servers keyword argument.Step 2: Identify correct syntax
"my_topic", bootstrap_servers='localhost:9092' uses correct string for topic and correct keyword bootstrap_servers with proper value.Final Answer:
"my_topic", bootstrap_servers='localhost:9092' -> Option DQuick Check:
Correct syntax uses bootstrap_servers keyword [OK]
- Omitting quotes around topic name
- Using wrong keyword like servers or bootstrap
- Passing topic name without quotes
What will be the output of this code snippet if the Kafka topic test has one message with value b'hello'?
from kafka import KafkaConsumer
consumer = KafkaConsumer("test", bootstrap_servers='localhost:9092', auto_offset_reset='earliest', group_id='group1')
for msg in consumer:
print(msg.value.decode('utf-8'))
breakSolution
Step 1: Understand message value type
Kafka messages are bytes, so msg.value is b'hello'.Step 2: Decode bytes to string
Calling decode('utf-8') converts b'hello' to 'hello' string, which is printed.Final Answer:
hello -> Option AQuick Check:
Decoded bytes print string [OK]
- Printing raw bytes without decoding
- Trying to decode string instead of bytes
- Expecting b'hello' printed as string
Identify the error in this Kafka consumer code snippet:
from kafka import KafkaConsumer
consumer = KafkaConsumer('topic1', bootstrap_servers='localhost:9092')
for message in consumer:
print(message.value.decode())
consumer.close()Solution
Step 1: Analyze loop and close call
The for loop on consumer is infinite; code never reaches consumer.close() after loop.Step 2: Understand consumer.close() usage
To close consumer properly, loop must break or use context manager; otherwise close() is unreachable.Final Answer:
The consumer.close() is called outside the loop and never reached -> Option BQuick Check:
Infinite loop blocks close() call [OK]
- Assuming decode() needs encoding argument
- Thinking group_id is mandatory
- Confusing poll() with iteration
You want to consume messages from two Kafka topics topicA and topicB using one Python KafkaConsumer instance. Which code snippet correctly sets this up?
from kafka import KafkaConsumer
consumer = KafkaConsumer(_____)
for msg in consumer:
print(f"Topic: {msg.topic}, Message: {msg.value.decode()}")Solution
Step 1: Check how to subscribe to multiple topics
KafkaConsumer accepts a list of topic names to subscribe to multiple topics.Step 2: Verify correct syntax for multiple topics
["topicA", "topicB"], bootstrap_servers='localhost:9092', auto_offset_reset='earliest', group_id='group1' correctly passes a list ["topicA", "topicB"] and required parameters.Final Answer:
["topicA", "topicB"], bootstrap_servers='localhost:9092', auto_offset_reset='earliest', group_id='group1' -> Option AQuick Check:
List of topics subscribes to multiple topics [OK]
- Passing topics as comma-separated string
- Using logical operators like and or ; between topics
- Omitting group_id for consumer group
Ready to prove it?
Pass the test and this pattern moves unknown
