Skip to content

Commit

Permalink
Update sse.py
Browse files Browse the repository at this point in the history
Add optional event_id parameter to SSE.send() method.
  • Loading branch information
Hamsanger committed Mar 8, 2024
1 parent d0a4cf8 commit 20bbe1c
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/microdot/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ def __init__(self):
self.event = asyncio.Event()
self.queue = []

async def send(self, data, event=None):
async def send(self, data, event=None, event_id=None):
"""Send an event to the client.
:param data: the data to send. It can be given as a string, bytes, dict
or list. Dictionaries and lists are serialized to JSON.
Any other types are converted to string before sending.
:param event: an optional event name, to send along with the data. If
given, it must be a string.
:param event_id: an optional event id, to send along with the data. If
given, it must be a string.
"""
if isinstance(data, (dict, list)):
data = json.dumps(data).encode()
Expand All @@ -28,6 +30,8 @@ async def send(self, data, event=None):
elif not isinstance(data, bytes):
data = str(data).encode()
data = b'data: ' + data + b'\n\n'
if event_id:
data = b'id: ' + event_id.encode() + b'\n' + data
if event:
data = b'event: ' + event.encode() + b'\n' + data
self.queue.append(data)
Expand Down

0 comments on commit 20bbe1c

Please sign in to comment.