A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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"""
2import asyncio
3from .responses import sse_event, now_iso
4
5
6async 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
36async 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})