Skip to content

Commit 6704050

Browse files
mahendramumrah
authored andcommitted
Finish making remaining files pep8 ready
1 parent 58288d9 commit 6704050

File tree

2 files changed

+168
-94
lines changed

2 files changed

+168
-94
lines changed

kafka/client.py

Lines changed: 109 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -10,43 +10,47 @@
1010

1111
from kafka.common import *
1212
from kafka.conn import KafkaConnection
13-
from kafka.protocol import KafkaProtocol
13+
from kafka.protocol import KafkaProtocol
1414

1515
log = logging.getLogger("kafka")
1616

17+
1718
class KafkaClient(object):
1819

1920
CLIENT_ID = "kafka-python"
20-
ID_GEN = count()
21+
ID_GEN = count()
2122

2223
def __init__(self, host, port, bufsize=4096):
23-
# We need one connection to bootstrap
24+
# We need one connection to bootstrap
2425
self.bufsize = bufsize
25-
self.conns = { # (host, port) -> KafkaConnection
26+
self.conns = { # (host, port) -> KafkaConnection
2627
(host, port): KafkaConnection(host, port, bufsize)
27-
}
28-
self.brokers = {} # broker_id -> BrokerMetadata
29-
self.topics_to_brokers = {} # topic_id -> broker_id
30-
self.topic_partitions = defaultdict(list) # topic_id -> [0, 1, 2, ...]
28+
}
29+
self.brokers = {} # broker_id -> BrokerMetadata
30+
self.topics_to_brokers = {} # topic_id -> broker_id
31+
self.topic_partitions = defaultdict(list) # topic_id -> [0, 1, 2, ...]
3132
self._load_metadata_for_topics()
3233

3334
##################
3435
# Private API #
3536
##################
3637

37-
3838
def _get_conn_for_broker(self, broker):
3939
"Get or create a connection to a broker"
4040
if (broker.host, broker.port) not in self.conns:
41-
self.conns[(broker.host, broker.port)] = KafkaConnection(broker.host, broker.port, self.bufsize)
41+
self.conns[(broker.host, broker.port)] = \
42+
KafkaConnection(broker.host, broker.port, self.bufsize)
43+
4244
return self.conns[(broker.host, broker.port)]
4345

4446
def _get_leader_for_partition(self, topic, partition):
4547
key = TopicAndPartition(topic, partition)
4648
if key not in self.topics_to_brokers:
4749
self._load_metadata_for_topics(topic)
50+
4851
if key not in self.topics_to_brokers:
4952
raise Exception("Partition does not exist: %s" % str(key))
53+
5054
return self.topics_to_brokers[key]
5155

5256
def _load_metadata_for_topics(self, *topics):
@@ -55,13 +59,18 @@ def _load_metadata_for_topics(self, *topics):
5559
recurse in the event of a retry.
5660
"""
5761
requestId = self._next_id()
58-
request = KafkaProtocol.encode_metadata_request(KafkaClient.CLIENT_ID, requestId, topics)
62+
request = KafkaProtocol.encode_metadata_request(KafkaClient.CLIENT_ID,
63+
requestId, topics)
64+
5965
response = self._send_broker_unaware_request(requestId, request)
6066
if response is None:
6167
raise Exception("All servers failed to process request")
68+
6269
(brokers, topics) = KafkaProtocol.decode_metadata_response(response)
70+
6371
log.debug("Broker metadata: %s", brokers)
6472
log.debug("Topic metadata: %s", topics)
73+
6574
self.brokers.update(brokers)
6675
self.topics_to_brokers = {}
6776
for topic, partitions in topics.items():
@@ -77,7 +86,8 @@ def _load_metadata_for_topics(self, *topics):
7786
time.sleep(1)
7887
self._load_metadata_for_topics(topic)
7988
else:
80-
self.topics_to_brokers[TopicAndPartition(topic, partition)] = brokers[meta.leader]
89+
topic_part = TopicAndPartition(topic, partition)
90+
self.topics_to_brokers[topic_part] = brokers[meta.leader]
8191
self.topic_partitions[topic].append(partition)
8292

8393
def _next_id(self):
@@ -86,41 +96,52 @@ def _next_id(self):
8696

8797
def _send_broker_unaware_request(self, requestId, request):
8898
"""
89-
Attempt to send a broker-agnostic request to one of the available brokers.
90-
Keep trying until you succeed.
99+
Attempt to send a broker-agnostic request to one of the available
100+
brokers. Keep trying until you succeed.
91101
"""
92102
for conn in self.conns.values():
93103
try:
94104
conn.send(requestId, request)
95105
response = conn.recv(requestId)
96106
return response
97107
except Exception, e:
98-
log.warning("Could not send request [%r] to server %s, trying next server: %s" % (request, conn, e))
108+
log.warning("Could not send request [%r] to server %s, "
109+
"trying next server: %s" % (request, conn, e))
99110
continue
111+
100112
return None
101113

102114
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn):
103115
"""
104-
Group a list of request payloads by topic+partition and send them to the
105-
leader broker for that partition using the supplied encode/decode functions
116+
Group a list of request payloads by topic+partition and send them to
117+
the leader broker for that partition using the supplied encode/decode
118+
functions
106119
107120
Params
108121
======
109-
payloads: list of object-like entities with a topic and partition attribute
110-
encode_fn: a method to encode the list of payloads to a request body, must accept
111-
client_id, correlation_id, and payloads as keyword arguments
112-
decode_fn: a method to decode a response body into response objects. The response
113-
objects must be object-like and have topic and partition attributes
122+
payloads: list of object-like entities with a topic and
123+
partition attribute
124+
encode_fn: a method to encode the list of payloads to a request body,
125+
must accept client_id, correlation_id, and payloads as
126+
keyword arguments
127+
decode_fn: a method to decode a response body into response objects.
128+
The response objects must be object-like and have topic
129+
and partition attributes
114130
115131
Return
116132
======
117133
List of response objects in the same order as the supplied payloads
118134
"""
135+
119136
# Group the requests by topic+partition
120137
original_keys = []
121138
payloads_by_broker = defaultdict(list)
139+
122140
for payload in payloads:
123-
payloads_by_broker[self._get_leader_for_partition(payload.topic, payload.partition)].append(payload)
141+
leader = self._get_leader_for_partition(payload.topic,
142+
payload.partition)
143+
144+
payloads_by_broker[leader].append(payload)
124145
original_keys.append((payload.topic, payload.partition))
125146

126147
# Accumulate the responses in a dictionary
@@ -130,7 +151,8 @@ def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn):
130151
for broker, payloads in payloads_by_broker.items():
131152
conn = self._get_conn_for_broker(broker)
132153
requestId = self._next_id()
133-
request = encoder_fn(client_id=KafkaClient.CLIENT_ID, correlation_id=requestId, payloads=payloads)
154+
request = encoder_fn(client_id=KafkaClient.CLIENT_ID,
155+
correlation_id=requestId, payloads=payloads)
134156

135157
# Send the request, recv the response
136158
conn.send(requestId, request)
@@ -149,100 +171,127 @@ def close(self):
149171
for conn in self.conns.values():
150172
conn.close()
151173

152-
def send_produce_request(self, payloads=[], acks=1, timeout=1000, fail_on_error=True, callback=None):
174+
def send_produce_request(self, payloads=[], acks=1, timeout=1000,
175+
fail_on_error=True, callback=None):
153176
"""
154177
Encode and send some ProduceRequests
155178
156-
ProduceRequests will be grouped by (topic, partition) and then sent to a specific
157-
broker. Output is a list of responses in the same order as the list of payloads
158-
specified
179+
ProduceRequests will be grouped by (topic, partition) and then
180+
sent to a specific broker. Output is a list of responses in the
181+
same order as the list of payloads specified
159182
160183
Params
161184
======
162185
payloads: list of ProduceRequest
163-
fail_on_error: boolean, should we raise an Exception if we encounter an API error?
164-
callback: function, instead of returning the ProduceResponse, first pass it through this function
186+
fail_on_error: boolean, should we raise an Exception if we
187+
encounter an API error?
188+
callback: function, instead of returning the ProduceResponse,
189+
first pass it through this function
165190
166191
Return
167192
======
168-
list of ProduceResponse or callback(ProduceResponse), in the order of input payloads
193+
list of ProduceResponse or callback(ProduceResponse), in the
194+
order of input payloads
169195
"""
170-
resps = self._send_broker_aware_request(payloads,
171-
partial(KafkaProtocol.encode_produce_request, acks=acks, timeout=timeout),
172-
KafkaProtocol.decode_produce_response)
196+
197+
encoder = partial(KafkaProtocol.encode_produce_request,
198+
acks=acks, timeout=timeout)
199+
decoder = KafkaProtocol.decode_produce_response
200+
resps = self._send_broker_aware_request(payloads, encoder, decoder)
201+
173202
out = []
174203
for resp in resps:
175204
# Check for errors
176-
if fail_on_error == True and resp.error != ErrorMapping.NO_ERROR:
177-
raise Exception("ProduceRequest for %s failed with errorcode=%d" %
178-
(TopicAndPartition(resp.topic, resp.partition), resp.error))
205+
if fail_on_error is True and resp.error != ErrorMapping.NO_ERROR:
206+
raise Exception("ProduceRequest for %s failed with "
207+
"errorcode=%d" % (
208+
TopicAndPartition(resp.topic, resp.partition),
209+
resp.error))
210+
179211
# Run the callback
180212
if callback is not None:
181213
out.append(callback(resp))
182214
else:
183215
out.append(resp)
184216
return out
185217

186-
def send_fetch_request(self, payloads=[], fail_on_error=True, callback=None):
218+
def send_fetch_request(self, payloads=[], fail_on_error=True,
219+
callback=None):
187220
"""
188221
Encode and send a FetchRequest
189-
190-
Payloads are grouped by topic and partition so they can be pipelined to the same
191-
brokers.
222+
223+
Payloads are grouped by topic and partition so they can be pipelined
224+
to the same brokers.
192225
"""
193226
resps = self._send_broker_aware_request(payloads,
194227
KafkaProtocol.encode_fetch_request,
195228
KafkaProtocol.decode_fetch_response)
229+
196230
out = []
197231
for resp in resps:
198232
# Check for errors
199-
if fail_on_error == True and resp.error != ErrorMapping.NO_ERROR:
200-
raise Exception("FetchRequest for %s failed with errorcode=%d" %
201-
(TopicAndPartition(resp.topic, resp.partition), resp.error))
233+
if fail_on_error is True and resp.error != ErrorMapping.NO_ERROR:
234+
raise Exception("FetchRequest for %s failed with "
235+
"errorcode=%d" % (
236+
TopicAndPartition(resp.topic, resp.partition),
237+
resp.error))
238+
202239
# Run the callback
203240
if callback is not None:
204241
out.append(callback(resp))
205242
else:
206243
out.append(resp)
207244
return out
208245

209-
210-
def send_offset_request(self, payloads=[], fail_on_error=True, callback=None):
246+
def send_offset_request(self, payloads=[], fail_on_error=True,
247+
callback=None):
211248
resps = self._send_broker_aware_request(payloads,
212249
KafkaProtocol.encode_offset_request,
213250
KafkaProtocol.decode_offset_response)
251+
214252
out = []
215253
for resp in resps:
216-
if fail_on_error == True and resp.error != ErrorMapping.NO_ERROR:
217-
raise Exception("OffsetRequest failed with errorcode=%s", resp.error)
254+
if fail_on_error is True and resp.error != ErrorMapping.NO_ERROR:
255+
raise Exception("OffsetRequest failed with errorcode=%s",
256+
resp.error)
218257
if callback is not None:
219258
out.append(callback(resp))
220259
else:
221260
out.append(resp)
222261
return out
223262

224-
def send_offset_commit_request(self, group, payloads=[], fail_on_error=True, callback=None):
225-
resps = self._send_broker_aware_request(payloads,
226-
partial(KafkaProtocol.encode_offset_commit_request, group=group),
227-
KafkaProtocol.decode_offset_commit_response)
263+
def send_offset_commit_request(self, group, payloads=[],
264+
fail_on_error=True, callback=None):
265+
encoder = partial(KafkaProtocol.encode_offset_commit_request,
266+
group=group)
267+
decoder = KafkaProtocol.decode_offset_commit_response
268+
resps = self._send_broker_aware_request(payloads, encoder, decoder)
269+
228270
out = []
229271
for resp in resps:
230-
if fail_on_error == True and resp.error != ErrorMapping.NO_ERROR:
231-
raise Exception("OffsetCommitRequest failed with errorcode=%s", resp.error)
272+
if fail_on_error is True and resp.error != ErrorMapping.NO_ERROR:
273+
raise Exception("OffsetCommitRequest failed with "
274+
"errorcode=%s", resp.error)
275+
232276
if callback is not None:
233277
out.append(callback(resp))
234278
else:
235279
out.append(resp)
236280
return out
237281

238-
def send_offset_fetch_request(self, group, payloads=[], fail_on_error=True, callback=None):
239-
resps = self._send_broker_aware_request(payloads,
240-
partial(KafkaProtocol.encode_offset_fetch_request, group=group),
241-
KafkaProtocol.decode_offset_fetch_response)
282+
def send_offset_fetch_request(self, group, payloads=[],
283+
fail_on_error=True, callback=None):
284+
285+
encoder = partial(KafkaProtocol.encode_offset_fetch_request,
286+
group=group)
287+
decoder = KafkaProtocol.decode_offset_fetch_response
288+
resps = self._send_broker_aware_request(payloads, encoder, decoder)
289+
242290
out = []
243291
for resp in resps:
244-
if fail_on_error == True and resp.error != ErrorMapping.NO_ERROR:
245-
raise Exception("OffsetCommitRequest failed with errorcode=%s", resp.error)
292+
if fail_on_error is True and resp.error != ErrorMapping.NO_ERROR:
293+
raise Exception("OffsetCommitRequest failed with errorcode=%s",
294+
resp.error)
246295
if callback is not None:
247296
out.append(callback(resp))
248297
else:

0 commit comments

Comments
 (0)