Skip to content

Commit 904d5fc

Browse files
authored
Add event ID to the SSE implementation (miguelgrinberg#213)
1 parent a0ea439 commit 904d5fc

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

src/microdot/sse.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,16 @@ def __init__(self):
1212
self.event = asyncio.Event()
1313
self.queue = []
1414

15-
async def send(self, data, event=None):
15+
async def send(self, data, event=None, event_id=None):
1616
"""Send an event to the client.
1717
1818
:param data: the data to send. It can be given as a string, bytes, dict
1919
or list. Dictionaries and lists are serialized to JSON.
2020
Any other types are converted to string before sending.
2121
:param event: an optional event name, to send along with the data. If
2222
given, it must be a string.
23+
:param event_id: an optional event id, to send along with the data. If
24+
given, it must be a string.
2325
"""
2426
if isinstance(data, (dict, list)):
2527
data = json.dumps(data).encode()
@@ -28,6 +30,8 @@ async def send(self, data, event=None):
2830
elif not isinstance(data, bytes):
2931
data = str(data).encode()
3032
data = b'data: ' + data + b'\n\n'
33+
if event_id:
34+
data = b'id: ' + event_id.encode() + b'\n' + data
3135
if event:
3236
data = b'event: ' + event.encode() + b'\n' + data
3337
self.queue.append(data)

tests/test_sse.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ def test_sse(self):
2323
async def handle_sse(request, sse):
2424
await sse.send('foo')
2525
await sse.send('bar', event='test')
26+
await sse.send('bar', event='test', event_id='id42')
27+
await sse.send('bar', event_id='id42')
2628
await sse.send({'foo': 'bar'})
2729
await sse.send([42, 'foo', 'bar'])
2830
await sse.send(ValueError('foo'))
@@ -34,6 +36,8 @@ async def handle_sse(request, sse):
3436
self.assertEqual(response.headers['Content-Type'], 'text/event-stream')
3537
self.assertEqual(response.text, ('data: foo\n\n'
3638
'event: test\ndata: bar\n\n'
39+
'event: test\nid: id42\ndata: bar\n\n'
40+
'id: id42\ndata: bar\n\n'
3741
'data: {"foo": "bar"}\n\n'
3842
'data: [42, "foo", "bar"]\n\n'
3943
'data: foo\n\n'

0 commit comments

Comments
 (0)