From 791439d96b28d5dd1b9d20d2921bd93ff02521fa Mon Sep 17 00:00:00 2001 From: Lorenz Diener Date: Mon, 29 Jan 2018 12:24:53 +0100 Subject: Remove state from handle_stream, fixes #119 --- mastodon/streaming.py | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) (limited to 'mastodon') diff --git a/mastodon/streaming.py b/mastodon/streaming.py index 4941ace..16b5375 100644 --- a/mastodon/streaming.py +++ b/mastodon/streaming.py @@ -41,40 +41,39 @@ class StreamListener(object): response; a requests response object with the open stream for reading. """ - self.event = {} + event = {} line_buffer = bytearray() for chunk in response.iter_content(chunk_size = 1): if chunk: if chunk == b'\n': - self.handle_line(line_buffer) + try: + line = line_buffer.decode('utf-8') + except UnicodeDecodeError as err: + six.raise_from( + MastodonMalformedEventError("Malformed UTF-8"), + err + ) + if line == '': + self._dispatch(event) + else: + event = self._parse_line(line, event) line_buffer = bytearray() else: line_buffer.extend(chunk) - def handle_line(self, raw_line): - try: - line = raw_line.decode('utf-8') - except UnicodeDecodeError as err: - six.raise_from( - MastodonMalformedEventError("Malformed UTF-8"), - err - ) - + def _parse_line(self, line, event): if line.startswith(':'): self.handle_heartbeat() - elif line == '': - # end of event - self._dispatch(self.event) - self.event = {} else: key, value = line.split(': ', 1) # According to the MDN spec, repeating the 'data' key # represents a newline(!) - if key in self.event: - self.event[key] += '\n' + value + if key in event: + event[key] += '\n' + value else: - self.event[key] = value - + event[key] = value + return event + def _dispatch(self, event): try: name = event['event'] -- cgit v1.2.3