Debian Codegraph @

docs/examples/responses/sse_responses.py

raw
1 from asyncio import sleep
2 from typing import AsyncGenerator
3
4 from litestar import Litestar, get
5 from litestar.response import ServerSentEvent, ServerSentEventMessage
6 from litestar.types import SSEData
7
8
9 async def my_generator() -> AsyncGenerator[SSEData, None]:
10 count = 0
11 while count < 10:
12 await sleep(0.01)
13 count += 1
14 # In the generator you can yield integers, strings, bytes, dictionaries, or ServerSentEventMessage objects
15 # dicts can have the following keys: data, event, id, retry, comment
16
17 # here we yield an integer
18 yield count
19 # here a string
20 yield str(count)
21 # here bytes
22 yield str(count).encode("utf-8")
23 # here a dictionary
24 yield {"data": 2 * count, "event": "event2", "retry": 10}
25 # here a ServerSentEventMessage object
26 yield ServerSentEventMessage(event="something-with-comment", retry=1000, comment="some comment")
27
28
29 @get(path="/count", sync_to_thread=False)
30 def sse_handler() -> ServerSentEvent:
31 return ServerSentEvent(my_generator())
32
33
34 app = Litestar(route_handlers=[sse_handler])