Remove state from handle_stream, fixes #119
This commit is contained in:
pare
42b1d8fa58
commit
791439d96b
S'han modificat 1 arxius amb 18 adicions i 19 eliminacions
|
@ -41,39 +41,38 @@ class StreamListener(object):
|
||||||
|
|
||||||
response; a requests response object with the open stream for reading.
|
response; a requests response object with the open stream for reading.
|
||||||
"""
|
"""
|
||||||
self.event = {}
|
event = {}
|
||||||
line_buffer = bytearray()
|
line_buffer = bytearray()
|
||||||
for chunk in response.iter_content(chunk_size = 1):
|
for chunk in response.iter_content(chunk_size = 1):
|
||||||
if chunk:
|
if chunk:
|
||||||
if chunk == b'\n':
|
if chunk == b'\n':
|
||||||
self.handle_line(line_buffer)
|
|
||||||
line_buffer = bytearray()
|
|
||||||
else:
|
|
||||||
line_buffer.extend(chunk)
|
|
||||||
|
|
||||||
def handle_line(self, raw_line):
|
|
||||||
try:
|
try:
|
||||||
line = raw_line.decode('utf-8')
|
line = line_buffer.decode('utf-8')
|
||||||
except UnicodeDecodeError as err:
|
except UnicodeDecodeError as err:
|
||||||
six.raise_from(
|
six.raise_from(
|
||||||
MastodonMalformedEventError("Malformed UTF-8"),
|
MastodonMalformedEventError("Malformed UTF-8"),
|
||||||
err
|
err
|
||||||
)
|
)
|
||||||
|
if line == '':
|
||||||
|
self._dispatch(event)
|
||||||
|
else:
|
||||||
|
event = self._parse_line(line, event)
|
||||||
|
line_buffer = bytearray()
|
||||||
|
else:
|
||||||
|
line_buffer.extend(chunk)
|
||||||
|
|
||||||
|
def _parse_line(self, line, event):
|
||||||
if line.startswith(':'):
|
if line.startswith(':'):
|
||||||
self.handle_heartbeat()
|
self.handle_heartbeat()
|
||||||
elif line == '':
|
|
||||||
# end of event
|
|
||||||
self._dispatch(self.event)
|
|
||||||
self.event = {}
|
|
||||||
else:
|
else:
|
||||||
key, value = line.split(': ', 1)
|
key, value = line.split(': ', 1)
|
||||||
# According to the MDN spec, repeating the 'data' key
|
# According to the MDN spec, repeating the 'data' key
|
||||||
# represents a newline(!)
|
# represents a newline(!)
|
||||||
if key in self.event:
|
if key in event:
|
||||||
self.event[key] += '\n' + value
|
event[key] += '\n' + value
|
||||||
else:
|
else:
|
||||||
self.event[key] = value
|
event[key] = value
|
||||||
|
return event
|
||||||
|
|
||||||
def _dispatch(self, event):
|
def _dispatch(self, event):
|
||||||
try:
|
try:
|
||||||
|
|
Loading…
Referencia en una nova incidència