Browse Source

Fix empty SSE data payload dropping the data: field

format_sse_event() built data: lines via data_str.splitlines(), which
returns [] for an empty string. An empty data payload (e.g. yielding
ServerSentEvent(raw_data='')) therefore emitted no data: field at all
and produced a malformed frame missing the data line and the documented
\n\n terminator. Emit a single empty data: line in that case.
pull/15948/head
devteamaegis 1 month ago
parent
commit
03cc11f65f
  1. 4
      fastapi/sse.py
  2. 8
      tests/test_sse.py

4
fastapi/sse.py

@ -213,7 +213,9 @@ def format_sse_event(
lines.append(f"event: {event}")
if data_str is not None:
for line in data_str.splitlines():
# An empty data payload must still emit a single `data:` field;
# `"".splitlines()` returns `[]`, which would drop the field entirely.
for line in data_str.splitlines() or [""]:
lines.append(f"data: {line}")
if id is not None:

8
tests/test_sse.py

@ -264,6 +264,14 @@ def test_data_and_raw_data_mutually_exclusive():
ServerSentEvent(data="json", raw_data="raw")
def test_format_sse_event_empty_data_str():
"""An empty data payload must still emit a single `data:` field and the
`\\n\\n` event terminator (`"".splitlines()` would otherwise drop it)."""
from fastapi.sse import format_sse_event
assert format_sse_event(data_str="") == b"data: \n\n"
def test_sse_on_router_included_in_app(client: TestClient):
response = client.get("/api/events")
assert response.status_code == 200

Loading…
Cancel
Save