| 1 |
import asyncio |
| 2 |
import json |
| 3 |
import logging |
| 4 |
import weakref |
| 5 |
from contextlib import suppress |
| 6 |
from datetime import datetime |
| 7 |
from functools import partial |
| 8 |
from typing import Any, Callable, Dict, Optional |
| 9 |
|
| 10 |
from aiohttp import web |
| 11 |
|
| 12 |
from aiohttp_sse import EventSourceResponse, sse_response |
| 13 |
|
| 14 |
streams_key = web.AppKey("streams_key", weakref.WeakSet["SSEResponse"]) |
| 15 |
worker_key = web.AppKey("worker_key", asyncio.Task[None]) |
| 16 |
|
| 17 |
|
| 18 |
class SSEResponse(EventSourceResponse): |
| 19 |
async def send_json( |
| 20 |
self, |
| 21 |
data: Dict[str, Any], |
| 22 |
id: Optional[str] = None, |
| 23 |
event: Optional[str] = None, |
| 24 |
retry: Optional[int] = None, |
| 25 |
json_dumps: Callable[[Any], str] = partial(json.dumps, indent=2), |
| 26 |
) -> None: |
| 27 |
await self.send(json_dumps(data), id=id, event=event, retry=retry) |
| 28 |
|
| 29 |
|
| 30 |
async def send_event( |
| 31 |
stream: SSEResponse, |
| 32 |
data: Dict[str, Any], |
| 33 |
event_id: str, |
| 34 |
) -> None: |
| 35 |
try: |
| 36 |
await stream.send_json(data, id=event_id) |
| 37 |
except Exception: |
| 38 |
logging.exception("Exception when sending event: %s", event_id) |
| 39 |
|
| 40 |
|
| 41 |
async def worker(app: web.Application) -> None: |
| 42 |
while True: |
| 43 |
now = datetime.now() |
| 44 |
delay = asyncio.create_task(asyncio.sleep(1)) # Fire |
| 45 |
|
| 46 |
fs = [] |
| 47 |
for stream in app[streams_key]: |
| 48 |
data = { |
| 49 |
"time": f"Server Time : {now}", |
| 50 |
"last_event_id": stream.last_event_id, |
| 51 |
} |
| 52 |
coro = send_event(stream, data, str(now.timestamp())) |
| 53 |
fs.append(coro) |
| 54 |
|
| 55 |
# Run in parallel |
| 56 |
await asyncio.gather(*fs) |
| 57 |
|
| 58 |
# Sleep 1s - n |
| 59 |
await delay |
| 60 |
|
| 61 |
|
| 62 |
async def on_startup(app: web.Application) -> None: |
| 63 |
app[streams_key] = weakref.WeakSet[SSEResponse]() |
| 64 |
app[worker_key] = asyncio.create_task(worker(app)) |
| 65 |
|
| 66 |
|
| 67 |
async def clean_up(app: web.Application) -> None: |
| 68 |
app[worker_key].cancel() |
| 69 |
with suppress(asyncio.CancelledError): |
| 70 |
await app[worker_key] |
| 71 |
|
| 72 |
|
| 73 |
async def on_shutdown(app: web.Application) -> None: |
| 74 |
waiters = [] |
| 75 |
for stream in app[streams_key]: |
| 76 |
stream.stop_streaming() |
| 77 |
waiters.append(stream.wait()) |
| 78 |
|
| 79 |
await asyncio.gather(*waiters, return_exceptions=True) |
| 80 |
app[streams_key].clear() |
| 81 |
|
| 82 |
|
| 83 |
async def hello(request: web.Request) -> web.StreamResponse: |
| 84 |
stream: SSEResponse = await sse_response(request, response_cls=SSEResponse) |
| 85 |
request.app[streams_key].add(stream) |
| 86 |
try: |
| 87 |
await stream.wait() |
| 88 |
finally: |
| 89 |
request.app[streams_key].discard(stream) |
| 90 |
return stream |
| 91 |
|
| 92 |
|
| 93 |
async def index(_request: web.Request) -> web.StreamResponse: |
| 94 |
d = """ |
| 95 |
<html> |
| 96 |
<head> |
| 97 |
<script> |
| 98 |
var eventSource = new EventSource("/hello"); |
| 99 |
eventSource.addEventListener("message", event => { |
| 100 |
document.getElementById("response").innerText = event.data; |
| 101 |
}); |
| 102 |
</script> |
| 103 |
</head> |
| 104 |
<body> |
| 105 |
<h1>Response from server:</h1> |
| 106 |
<pre id="response"></pre> |
| 107 |
</body> |
| 108 |
</html> |
| 109 |
""" |
| 110 |
return web.Response(text=d, content_type="text/html") |
| 111 |
|
| 112 |
|
| 113 |
if __name__ == "__main__": |
| 114 |
app = web.Application() |
| 115 |
|
| 116 |
app.on_startup.append(on_startup) |
| 117 |
app.on_shutdown.append(on_shutdown) |
| 118 |
app.on_cleanup.append(clean_up) |
| 119 |
|
| 120 |
app.router.add_route("GET", "/hello", hello) |
| 121 |
app.router.add_route("GET", "/", index) |
| 122 |
web.run_app(app, host="127.0.0.1", port=8080) |