1 | #!/usr/bin/env python
|
2 | import sys
|
3 | import os
|
4 | import signal
|
5 | import pathlib
|
6 | import contextvars
|
7 |
|
8 | from aiohttp import web
|
9 |
|
10 |
|
11 | _ws = "_websockets"
|
12 |
|
13 |
|
14 | async 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 |
|
27 | async def reloader(request):
|
28 | for socket in request.app[_ws]:
|
29 | await socket.send_str("reload")
|
30 | return web.Response()
|
31 |
|
32 |
|
33 | def 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 |
|
51 | app = web.Application(middlewares=load_middleware(static_path="gen"))
|
52 | app.add_routes([web.get("/ws", websocket)])
|
53 | app.add_routes([web.post("/reload", reloader)])
|
54 | app.add_routes([web.static("/", "gen", show_index=False)])
|
55 | app[_ws] = []
|
56 |
|
57 | web.run_app(app, port=8888)
|