From fe3a20170c1413f7d4dfb9c41ceb0e4b50d41a59 Mon Sep 17 00:00:00 2001 From: ThePsyjo Date: Fri, 13 Aug 2021 16:54:17 +0200 Subject: [PATCH] Add and use _chunker method when sending metrics --- pyzabbix/sender.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/pyzabbix/sender.py b/pyzabbix/sender.py index 250c3ab..124f88f 100644 --- a/pyzabbix/sender.py +++ b/pyzabbix/sender.py @@ -427,6 +427,27 @@ def _chunk_send(self, metrics): raise socket.error(response) return response + + def _chunker(self, iterable): + """Batch `iterable` into chunks of size `chunk_size`. + + :type iterable: Iterable + :param iterable: any iterable to be chunked + + :rtype: Iterable + :return: Chunk generator + """ + if self.chunk_size is None: + yield iterable + return + chunk = [] + for item in iterable: + chunk.append(item) + if len(chunk) >= self.chunk_size: + yield chunk + chunk = [] + if chunk: + yield chunk def send(self, metrics): """Send the metrics to zabbix server. @@ -439,6 +460,6 @@ def send(self, metrics): :return: Parsed response from Zabbix Server """ result = ZabbixResponse() - for m in range(0, len(metrics), self.chunk_size): - result.parse(self._chunk_send(metrics[m:m + self.chunk_size])) + for chunk in self._chunker(metrics): + result.parse(self._chunk_send(chunk)) return result