-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
52 lines (40 loc) · 1.16 KB
/
main.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
import datetime
import json
import uuid
from typing import Iterable
import asyncio
from fastapi import FastAPI, Request
from sse_starlette.sse import EventSourceResponse
from starlette.responses import FileResponse
app = FastAPI()
@app.get("/")
async def read_index():
return FileResponse("index.html")
STREAM_DELAY = 1 # second
RETRY_TIMEOUT = 15000 # millisecond
def get_new_messages() -> Iterable:
return [
{
"event": "new_message",
"retry": RETRY_TIMEOUT,
"data": json.dumps(
{
"message": "test message",
"datetime": datetime.datetime.now().isoformat(
sep="T", timespec="auto"
),
}
),
"id": uuid.uuid4(),
}
]
async def event_generator(request: Request):
while True:
if await request.is_disconnected():
break
for message in get_new_messages():
yield message
await asyncio.sleep(STREAM_DELAY)
@app.get("/stream")
async def message_stream(request: Request):
return EventSourceResponse(event_generator(request))