MediumParsingPython 3
SSE Event Parser
Parse chunked server-sent events while handling split lines, comments, and multiline data payloads.
35m3 sample tests9 hidden tests
Parse server-sent event (SSE) chunks into complete data payloads.
Requirements
- Define
parse_sse_events(chunks). chunksis a list of already-decoded strings from a streaming response, possibly including empty chunks.- Events are separated by a blank line.
- Lines may end with LF or CRLF; strip a trailing
\rfrom each completed line before field handling. - Lines beginning with
data:add payload text. After the colon, if the next character is a single space, remove that one space and keep any further spaces (WHATWG SSE rule). - Multiple
data:lines in one event join with\n. - An event with
data:but no payload emits"". A block with nodata:lines emits nothing. - Lines beginning with
:are comments and should be ignored. - Ignore other fields such as
event:andid:. - Return a list of completed event data strings.
- Ignore an incomplete final event without a trailing blank line.
Example
python
chunks = ["data: hello\n", "data: world\n\n"]
assert parse_sse_events(chunks) == ["hello\nworld"]Constraints
- Chunk boundaries may split lines anywhere.
- CRLF may split between chunks; it must still count as one line ending.
- Use an explicit state machine or careful line buffering.
- Don't require network or async code.
- This deliberately implements only the stated SSE subset. Bare CR endings, a leading byte order mark, and colonless
datafields are outside this exercise. The WHATWG standard covers those cases; production clients also need incremental UTF-8 decoding, event IDs, reconnect handling, and bounded buffering.
Editor