|
| 1 | +""" |
| 2 | +Server Side Events (SSE) client for Python. |
| 3 | +
|
| 4 | +Provides a generator of SSE received through an existing HTTP response. |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | + |
| 9 | +__author__ = 'Maxime Petazzoni <maxime.petazzoni@bulix.org>' |
| 10 | +__email__ = 'maxime.petazzoni@bulix.org' |
| 11 | +__all__ = ['SSEClient'] |
| 12 | + |
| 13 | +_FIELD_SEPARATOR = ':' |
| 14 | + |
| 15 | + |
| 16 | +class SSEClient(object): |
| 17 | + """Implementation of a SSE client. |
| 18 | +
|
| 19 | + See http://www.w3.org/TR/2009/WD-eventsource-20091029/ for the |
| 20 | + specification. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, event_source, char_enc='utf-8'): |
| 24 | + """Initialize the SSE client over an existing, ready to consume |
| 25 | + event source. |
| 26 | +
|
| 27 | + The event source is expected to be a binary stream and have a close() |
| 28 | + method. That would usually be something that implements |
| 29 | + io.BinaryIOBase, like an httplib or urllib3 HTTPResponse object. |
| 30 | + """ |
| 31 | + self._logger = logging.getLogger(self.__class__.__module__) |
| 32 | + self._logger.debug('Initialized SSE client from event source %s', |
| 33 | + event_source) |
| 34 | + self._event_source = event_source |
| 35 | + self._char_enc = char_enc |
| 36 | + |
| 37 | + def _read(self): |
| 38 | + """Read the incoming event source stream and yield event chunks. |
| 39 | +
|
| 40 | + Unfortunately it is possible for some servers to decide to break an |
| 41 | + event into multiple HTTP chunks in the response. It is thus necessary |
| 42 | + to correctly stitch together consecutive response chunks and find the |
| 43 | + SSE delimiter (empty new line) to yield full, correct event chunks.""" |
| 44 | + data = b'' |
| 45 | + for chunk in self._event_source: |
| 46 | + for line in chunk.splitlines(True): |
| 47 | + data += line |
| 48 | + if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')): |
| 49 | + yield data |
| 50 | + data = b'' |
| 51 | + if data: |
| 52 | + yield data |
| 53 | + |
| 54 | + def events(self): |
| 55 | + for chunk in self._read(): |
| 56 | + event = Event() |
| 57 | + # Split before decoding so splitlines() only uses \r and \n |
| 58 | + for line in chunk.splitlines(): |
| 59 | + # Decode the line. |
| 60 | + line = line.decode(self._char_enc) |
| 61 | + |
| 62 | + # Lines starting with a separator are comments and are to be |
| 63 | + # ignored. |
| 64 | + if not line.strip() or line.startswith(_FIELD_SEPARATOR): |
| 65 | + continue |
| 66 | + |
| 67 | + data = line.split(_FIELD_SEPARATOR, 1) |
| 68 | + field = data[0] |
| 69 | + |
| 70 | + # Ignore unknown fields. |
| 71 | + if field not in event.__dict__: |
| 72 | + self._logger.debug('Saw invalid field %s while parsing ' |
| 73 | + 'Server Side Event', field) |
| 74 | + continue |
| 75 | + |
| 76 | + if len(data) > 1: |
| 77 | + # From the spec: |
| 78 | + # "If value starts with a single U+0020 SPACE character, |
| 79 | + # remove it from value." |
| 80 | + if data[1].startswith(' '): |
| 81 | + value = data[1][1:] |
| 82 | + else: |
| 83 | + value = data[1] |
| 84 | + else: |
| 85 | + # If no value is present after the separator, |
| 86 | + # assume an empty value. |
| 87 | + value = '' |
| 88 | + |
| 89 | + # The data field may come over multiple lines and their values |
| 90 | + # are concatenated with each other. |
| 91 | + if field == 'data': |
| 92 | + event.__dict__[field] += value + '\n' |
| 93 | + else: |
| 94 | + event.__dict__[field] = value |
| 95 | + |
| 96 | + # Events with no data are not dispatched. |
| 97 | + if not event.data: |
| 98 | + continue |
| 99 | + |
| 100 | + # If the data field ends with a newline, remove it. |
| 101 | + if event.data.endswith('\n'): |
| 102 | + event.data = event.data[0:-1] |
| 103 | + |
| 104 | + # Empty event names default to 'message' |
| 105 | + event.event = event.event or 'message' |
| 106 | + |
| 107 | + # Dispatch the event |
| 108 | + self._logger.debug('Dispatching %s...', event) |
| 109 | + yield event |
| 110 | + |
| 111 | + def close(self): |
| 112 | + """Manually close the event source stream.""" |
| 113 | + self._event_source.close() |
| 114 | + |
| 115 | + |
| 116 | +class Event(object): |
| 117 | + """Representation of an event from the event stream.""" |
| 118 | + |
| 119 | + def __init__(self, id=None, event='message', data='', retry=None): |
| 120 | + self.id = id |
| 121 | + self.event = event |
| 122 | + self.data = data |
| 123 | + self.retry = retry |
| 124 | + |
| 125 | + def __str__(self): |
| 126 | + s = '{0} event'.format(self.event) |
| 127 | + if self.id: |
| 128 | + s += ' #{0}'.format(self.id) |
| 129 | + if self.data: |
| 130 | + s += ', {0} byte{1}'.format(len(self.data), |
| 131 | + 's' if len(self.data) else '') |
| 132 | + else: |
| 133 | + s += ', no data' |
| 134 | + if self.retry: |
| 135 | + s += ', retry in {0}ms'.format(self.retry) |
| 136 | + return s |
0 commit comments