askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
sse.py · 1.8 KB · 58 lines
| 1 | """Server-Sent Events (SSE) support""" |
| 2 | import asyncio |
| 3 | from .responses import sse_event, now_iso |
| 4 | |
| 5 | |
| 6 | async def sse_counter(scope, receive, send): |
| 7 | """Example SSE endpoint that sends a counter every second""" |
| 8 | assert scope["type"] == "http" |
| 9 | |
| 10 | headers = [ |
| 11 | (b"content-type", b"text/event-stream"), |
| 12 | (b"cache-control", b"no-cache"), |
| 13 | (b"connection", b"keep-alive"), |
| 14 | (b"x-accel-buffering", b"no"), # Disable nginx buffering |
| 15 | ] |
| 16 | |
| 17 | await send({"type": "http.response.start", "status": 200, "headers": headers}) |
| 18 | |
| 19 | i = 0 |
| 20 | try: |
| 21 | while True: |
| 22 | payload = sse_event( |
| 23 | f'{{"count":{i},"ts":"{now_iso()}"}}', event="tick", id=str(i) |
| 24 | ) |
| 25 | await send( |
| 26 | {"type": "http.response.body", "body": payload, "more_body": True} |
| 27 | ) |
| 28 | i += 1 |
| 29 | await asyncio.sleep(1.0) |
| 30 | except asyncio.CancelledError: |
| 31 | pass |
| 32 | finally: |
| 33 | await send({"type": "http.response.body", "body": b"", "more_body": False}) |
| 34 | |
| 35 | |
| 36 | async def sse_stream(scope, receive, send, generator): |
| 37 | """Generic SSE streaming from an async generator""" |
| 38 | assert scope["type"] == "http" |
| 39 | |
| 40 | headers = [ |
| 41 | (b"content-type", b"text/event-stream"), |
| 42 | (b"cache-control", b"no-cache"), |
| 43 | (b"connection", b"keep-alive"), |
| 44 | (b"x-accel-buffering", b"no"), |
| 45 | ] |
| 46 | |
| 47 | await send({"type": "http.response.start", "status": 200, "headers": headers}) |
| 48 | |
| 49 | try: |
| 50 | async for event_data in generator: |
| 51 | payload = sse_event(event_data) |
| 52 | await send( |
| 53 | {"type": "http.response.body", "body": payload, "more_body": True} |
| 54 | ) |
| 55 | except asyncio.CancelledError: |
| 56 | pass |
| 57 | finally: |
| 58 | await send({"type": "http.response.body", "body": b"", "more_body": False}) |