Pythonserver.py -rwxr-xr-x 1.5 KiB
1#!/usr/bin/env python
2import sys
3import os
4import signal
5import pathlib
6import contextvars
7
8from aiohttp import web
9
10
11_ws = "_websockets"
12
13
14async def websocket(request):
15 ws = web.WebSocketResponse()
16 await ws.prepare(request)
17 request.app[_ws].append(ws)
18 try:
19 async for msg in ws:
20 print("echo: ", msg.data)
21 ws.send_str(msg.data)
22 finally:
23 request.app[_ws].pop()
24 return ws
25
26
27async def reloader(request):
28 for socket in request.app[_ws]:
29 await socket.send_str("reload")
30 return web.Response()
31
32
33def load_middleware(static_path="gen"):
34 async def serve_indexes(request: web.Request, handler):
35 if request.path == "/ws":
36 return await handler(request)
37 if request.path == "/reload":
38 return await handler(request)
39 relative_file_path = pathlib.Path(request.path).relative_to('/')
40 file_path = static_path / relative_file_path
41 if not file_path.exists():
42 return web.HTTPNotFound()
43 if file_path.is_dir():
44 file_path /= "index.html"
45 if not file_path.exists():
46 return web.HTTPNotFound()
47 return web.FileResponse(file_path)
48 return [web.middleware(serve_indexes)]
49
50
51app = web.Application(middlewares=load_middleware(static_path="gen"))
52app.add_routes([web.get("/ws", websocket)])
53app.add_routes([web.post("/reload", reloader)])
54app.add_routes([web.static("/", "gen", show_index=False)])
55app[_ws] = []
56
57web.run_app(app, port=8888)