SSE Stream Parser

Start Timer

0:00:00

Upvote
0
Downvote
Save question
View comments

Write a generator function called parse_sse_stream that takes an iterable of bytes chunks from a streaming API and yields each JSON payload as a parsed object as soon as its event is complete.

The stream uses server-sent events. Each event is a block of UTF-8 lines that ends with a blank line (\n\n), and its JSON is on the line that starts with data:. Ignore every other line, such as : keep-alive comments, and stop when the payload is [DONE]. Network buffers can split the stream at any byte.

Note: Don’t read the whole stream into memory. An unfinished event at the end of the stream is dropped.

Example:

Input:

chunks = [
    b'data: {"id": 1, "text": "caf\xc3',
    b'\xa9"}\n\n: keep-alive\n\ndata: {"id"',
    b': 2}\n',
    b'\ndata: [DONE]\n\n',
]

Output:

list(parse_sse_stream(chunks)) -> [{'id': 1, 'text': 'café'}, {'id': 2}]
.
.
.
.
.


Comments

Loading comments