-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
69 lines (56 loc) · 1.55 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import asyncio
import logging
import random
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from sse_starlette.sse import EventSourceResponse
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
COUNTER = {"#of_news": 0, "#of_subscribers": 0}
async def event_generator(request):
"""Generate status events with current # of users or news"""
while True:
if await request.is_disconnected():
logger.debug("Request disconnected")
break
event = random.choice(["#of_news", "#of_subscribers"])
COUNTER[event] += 1
yield {
"event": event,
"retry": 5000, # miliseconds
"data": str(COUNTER[event]), # HTML representation
}
logger.debug(f"{event}: {COUNTER[event]}")
await asyncio.sleep(0.3) # in seconds
app = FastAPI()
@app.get("/")
async def home():
return HTMLResponse(
"""
<html>
<head>
<script src="https://unpkg.com/htmx.org@1.4.1"></script>
</head>
<body hx-sse="connect:/status_updates">
<h1></>htmx and SSE with FastAPI</h1>
<table>
<tr>
<td>News</td>
<td hx-sse="swap:#of_news">0</td>
</tr>
<tr>
<td>Operating</td>
<td>24/7</td>
</tr>
<tr>
<td>Subscribers</td>
<td hx-sse="swap:#of_subscribers">0</td>
</tr>
</table>
</body>
</html>
"""
)
@app.get("/status_updates")
async def runStatus(request: Request):
return EventSourceResponse(event_generator(request))