Skip to content

Commit

Permalink
fix: sending empty data in sse in js client (#3176)
Browse files Browse the repository at this point in the history
fix sending empty data in sse
  • Loading branch information
euri10 authored Mar 8, 2024
1 parent 1767779 commit 65efff1
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 1 deletion.
2 changes: 1 addition & 1 deletion litestar/response/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async def _async_generator(self) -> AsyncGenerator[bytes, None]:

@dataclass
class ServerSentEventMessage:
data: str | int | bytes | None = None
data: str | int | bytes | None = ""
event: str | None = None
id: int | str | None = None
retry: int | None = None
Expand Down
Empty file added test_apps/sse/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions test_apps/sse/sse.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Server-Sent Events</h2>
<div id="output"></div>
<script>
if (typeof EventSource !== "undefined") {
var eventSource = new EventSource("http://localhost:8000/test_sse_empty");
eventSource.onmessage = function (event) {
console.log(event.data);
document.getElementById("output").innerHTML += event.data + "<br>";
};
eventSource.addEventListener("empty", (ev) => {
console.log("empty arrived");
document.getElementById("output").innerHTML += "endx arrived" + "<br>";
eventSource.close();
});

eventSource.addEventListener("error", (err) => {
console.error(err)
document.getElementById("output").innerHTML += "error: " + err + "<br>";
})
} else {
document.getElementById("output").innerHTML =
// If browser does not support SSE
"Sorry, the browser does not support SSE";
}
</script>
</body>
</html>
23 changes: 23 additions & 0 deletions test_apps/sse/sse_empty.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import AsyncIterator

import uvicorn

from litestar import Litestar, get
from litestar.config.cors import CORSConfig
from litestar.response import ServerSentEvent, ServerSentEventMessage
from litestar.types import SSEData


@get("/test_sse_empty")
async def handler() -> ServerSentEvent:
async def generate() -> AsyncIterator[SSEData]:
event = ServerSentEventMessage(event="empty")
yield event

return ServerSentEvent(generate())


app = Litestar(route_handlers=[handler], cors_config=CORSConfig(allow_origins=["*"]))

if __name__ == "__main__":
uvicorn.run("sse_empty:app")

0 comments on commit 65efff1

Please sign in to comment.