aiohttp-sse

2.2.0 · active · verified Wed Apr 15

aiohttp-sse provides server-sent events support for aiohttp. It allows building real-time web applications where the server pushes updates to clients over a single HTTP connection. The current version is 2.2.0, and it has a relatively active release cadence with several updates per year, focusing on Python and aiohttp compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up an aiohttp web server that serves an HTML page. The HTML page contains JavaScript that connects to a '/hello' endpoint via Server-Sent Events. The '/hello' endpoint uses `aiohttp-sse`'s `sse_response` context manager to continuously send the current server time to the connected client.

import asyncio
import json
from datetime import datetime
from aiohttp import web
from aiohttp_sse import sse_response

async def hello(request: web.Request) -> web.StreamResponse:
    async with sse_response(request) as resp:
        # Optional: send an initial comment to stop browser loading spinner
        await resp.send(None, event='comment', data='connected')
        while resp.is_connected():
            time_dict = {"time": f"Server Time : {datetime.now()}"}
            data = json.dumps(time_dict, indent=2)
            print(data)
            await resp.send(data)
            await asyncio.sleep(1)
    return resp

async def index(_request: web.Request) -> web.Response:
    html = """
<html>
<body>
    <script>
        var eventSource = new EventSource("/hello");
        eventSource.addEventListener("message", event => {
            document.getElementById("response").innerText = event.data;
        });
    </script>
    <h1>Response from server:</h1>
    <div id="response"></div>
</body>
</html>
"""
    return web.Response(text=html, content_type="text/html")

app = web.Application()
app.router.add_route("GET", "/hello", hello)
app.router.add_route("GET", "/", index)

if __name__ == '__main__':
    web.run_app(app, host="127.0.0.1", port=8080)

view raw JSON →