#!/usr/bin/env python import sys import os import signal import pathlib import contextvars from aiohttp import web _ws = "_websockets" async def websocket(request): ws = web.WebSocketResponse() await ws.prepare(request) request.app[_ws].append(ws) try: async for msg in ws: print("echo: ", msg.data) ws.send_str(msg.data) finally: request.app[_ws].pop() return ws async def reloader(request): for socket in request.app[_ws]: await socket.send_str("reload") return web.Response() def load_middleware(static_path="gen"): async def serve_indexes(request: web.Request, handler): if request.path == "/ws": return await handler(request) if request.path == "/reload": return await handler(request) relative_file_path = pathlib.Path(request.path).relative_to('/') file_path = static_path / relative_file_path if not file_path.exists(): return web.HTTPNotFound() if file_path.is_dir(): file_path /= "index.html" if not file_path.exists(): return web.HTTPNotFound() return web.FileResponse(file_path) return [web.middleware(serve_indexes)] app = web.Application(middlewares=load_middleware(static_path="gen")) app.add_routes([web.get("/ws", websocket)]) app.add_routes([web.post("/reload", reloader)]) app.add_routes([web.static("/", "gen", show_index=False)]) app[_ws] = [] web.run_app(app, port=8888)