Skip to content

Commit 7db28af

Browse files
Update server-sent-events.md
1 parent 6a83058 commit 7db28af

1 file changed

Lines changed: 41 additions & 2 deletions

File tree

docs/server-sent-events.md

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ use the built-in features for server-sent events.
1111

1212
!!! tip
1313
Older versions of the web framework can also be configured to use SSE,
14-
because they already supported response streaming, but this requires
15-
writing functions that generate the right bytes.
14+
because they all support response streaming, but don't offer dedicated
15+
features to simplify their use.
1616

1717
## Defining a server-sent events route
1818

@@ -202,6 +202,45 @@ async def events_handler(request: Request) -> AsyncIterable[ServerSentEvent]:
202202
Refer to the [server-sent events example](https://github.com/Neoteroi/BlackSheep-Examples/tree/main/server-sent-events) for an example that handles application shutdown and client
203203
disconnections, and also presents a basic example in JavaScript to use SSE.
204204

205+
## Using SSE in older versions of BlackSheep
206+
207+
The following example illustrates how to use server-sent events in older
208+
versions of the web framework.
209+
210+
```python
211+
212+
import asyncio
213+
import json
214+
from blacksheep import Application, Response, StreamedContent, get
215+
216+
app = Application()
217+
218+
219+
@get("/events")
220+
def events_handler(request):
221+
async def provider():
222+
i = 0
223+
while True:
224+
# TODO: implement way to detect if the process is stopping,
225+
# and if the request is still active,
226+
# use await request.is_disconnected() if available...
227+
obj = {"message": f"Hello World {i}"}
228+
yield b"data: " + json.dumps(obj).encode("utf8") + b"\r\n\r\n"
229+
i += 1
230+
231+
try:
232+
await asyncio.sleep(1)
233+
except asyncio.CancelledError:
234+
pass
235+
236+
return Response(
237+
200,
238+
headers=[(b"Cache-Control", b"no-cache"), (b"Connection", b"Keep-Alive")],
239+
content=StreamedContent(b"text/event-stream", provider),
240+
)
241+
242+
```
243+
205244
## Related technologies
206245

207246
Server-sent events are often related to WebSockets, which instead enable

0 commit comments

Comments
 (0)