MediumParsingPython 3
SSE Event Parser
Parse chunked server-sent events while handling split lines, comments, and multiline data payloads.
35m3 sample tests6 hidden tests
Parse server-sent event chunks into complete data payloads.
Requirements
- Define
parse_sse_events(chunks). chunksis a list of strings from a streaming response.- 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. - 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
1chunks = ["data: hello\n", "data: world\n\n"]
2assert parse_sse_events(chunks) == ["hello\nworld"]Constraints
- Chunk boundaries may split lines anywhere.
- Use an explicit state machine or careful line buffering.
- Don't require network or async code.
Editor