SSE Client with Reconnect Parser
Parse text/event-stream frames into structured events and wrap the HTTP read loop with bounded reconnect attempts and backoff.
Code
import json
import time
import urllib.error
import urllib.request
from collections.abc import Iterable, Iterator
def parse_sse(lines: Iterable[str]) -> Iterator[dict[str, str]]:
event: dict[str, str] = {}
data: list[str] = []
for raw in lines:
line = raw.rstrip("\r\n")
if not line:
if data:
event["data"] = "\n".join(data)
yield event
event, data = {}, []
continue
if line.startswith(":"):
continue
field, _, value = line.partition(":")
value = value.lstrip(" ")
if field == "data":
data.append(value)
elif field:
event[field] = value
if data:
event["data"] = "\n".join(data)
yield event
def iter_sse(
url: str, retries: int = 3, backoff: float = 0.5
) -> Iterator[dict[str, str]]:
attempt = 0
while True:
try:
request = urllib.request.Request(
url, headers={"Accept": "text/event-stream"}
)
with urllib.request.urlopen(request, timeout=30) as response:
yield from parse_sse(line.decode("utf-8") for line in response)
return
except (OSError, urllib.error.URLError):
attempt += 1
if attempt > retries:
raise
time.sleep(backoff * attempt)
FIXTURE = """event: build
id: 7
data: {"status": "ok"}
data: second line
"""
if __name__ == "__main__":
events = list(parse_sse(FIXTURE.splitlines()))
print(events)
for event in events:
first_line = event["data"].splitlines()[0]
print(event.get("event", "message"), json.loads(first_line))
How the snippet works
SSE Client with Reconnect Parser keeps everything in the functions parse_sse and iter_sse.
The cycling part of this snippet is for raw in lines. From urllib it pulls Iterable, Iterator — the imports name exactly which library surface the snippet touches. time appears at a raise inside an except handler — it fires only while that failure type is already being handled.
What to watch for
- Dependency check:
urllib— not built-in, must be present in the project. - The guard
attempt > retriesshort-circuits the flow with an earlyraisewhen its condition holds.
Applying it
The main signature reads def parse_sse(lines: Iterable[str]) -> Iterator[dict[str, str]]
Statements that matter
yield from parse_sse(line.decode("utf-8") for line in response)
return
except (OSError, urllib.error.URLError):
attempt += 1
if attempt > retries:
raise
time.sleep(backoff * attempt)
FIXTURE = """event: build
id: 7
data: {"status": "ok"}
with urllib.request.urlopen(request, timeout=30) as response:
yield from parse_sse(line.decode("utf-8") for line in response)
def iter_sse(
url: str, retries: int = 3, backoff: float = 0.5
) -> Iterator[dict[str, str]]:
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- When is the exception raised?
- Inside an `except` handler — the `time` fires only while that failure type is already being handled, not on its own trigger.
- Does this require external packages?
- Yes — `urllib`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.