webpnp/main.py
2020-04-16 23:54:06 +02:00

92 lines
2.0 KiB
Python

import aiohttp.web
routes = aiohttp.web.RouteTableDef()
routes.static('/static', 'static')
admintoken = "ae33fd8cc4fdcb1ff50ba42ff48046a7"
CLIENT_REGEX = r'/{client:[a-zA-Z0-9]{16}}'
meta_dict = {}
def get_client(request: aiohttp.web.Request):
client = request.match_info.get("client", None)
if not client:
raise aiohttp.web.HTTPBadRequest()
return client
@routes.get(CLIENT_REGEX)
async def handler(request: aiohttp.web.Request):
# this handler prevents people missing trailing slashes
client = get_client(request)
raise aiohttp.web.HTTPFound(f"/{client}/")
@routes.get(CLIENT_REGEX + '/')
async def handler(request: aiohttp.web.Request):
client = get_client(request)
print(f"{client=} accessed")
return aiohttp.web.FileResponse('ui.html')
async def handle_request(data, client):
return "foo" in data
@routes.post(CLIENT_REGEX + '/api')
async def handler(request: aiohttp.web.Request):
client = get_client(request)
data = await request.json()
print(f'{client=} {data=}')
ok = await handle_request(data, client)
if ok:
# return aiohttp.web.json_response({"x" : x})
return aiohttp.web.Response(status=200)
else:
return aiohttp.web.Response(status=400)
@routes.get(CLIENT_REGEX + '/ws')
async def _(request: aiohttp.web.Request):
client = get_client(request)
ws = aiohttp.web.WebSocketResponse(heartbeat=10)
await ws.prepare(request)
print(f'model.subscribe({client}, ws)')
async for msg in ws:
print(f'[WS] client sent {msg=}')
print(f'model.unsubscribe(ws)')
return ws
@routes.get(f"/api/{admintoken}")
async def handler(request: aiohttp.web.Request):
del request # unused
return aiohttp.web.json_response(meta_dict)
@routes.get('/')
async def handler(request):
del request # unused
return aiohttp.web.FileResponse('index.html')
if __name__ == '__main__':
app = aiohttp.web.Application()
app.add_routes(routes)
aiohttp.web.run_app(app, port=42042)
print("should save state")