add websocket_handler and time_response

Signed-off-by: kirill <kirill.milkin05@mail.ru>
pull/3/head
kirill 2 years ago
parent a7eee835b8
commit a946dd42c8
  1. 47
      demo/views/frontend.py

@ -15,6 +15,8 @@ async def time_response(ws: WebSocketResponse, delay: int = 60):
await asyncio.sleep(delay) await asyncio.sleep(delay)
except ConnectionResetError: except ConnectionResetError:
await asyncio.sleep(delay) await asyncio.sleep(delay)
@template('index.html') @template('index.html')
async def index(request): async def index(request):
return {} return {}
@ -24,28 +26,31 @@ async def index_2(request):
return {} return {}
async def websocket_handler(request): async def websocket_handler(request):
ws: WebSocketResponse = WebSocketResponse() ws: WebSocketResponse = WebSocketResponse()
await ws.prepare(request) await ws.prepare(request)
asyncio.create_task(time_response(ws)) asyncio.create_task(time_response(ws))
async for msg in ws: async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT: if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close': if msg.data == 'close':
await ws.close() await ws.close()
else: else:
await ws.send_str(f'Вы послали: {msg.data}') await ws.send_str(f'Вы послали: {msg.data}')
elif msg.type == WSMsgType.ERROR: elif msg.type == WSMsgType.ERROR:
print('ws connection closed with exception %s' % print('ws connection closed with exception %s' %
ws.exception()) ws.exception())
print('websocket connection closed')
return ws
print('websocket connection closed')
return ws
async def button_clicked(request): async def button_clicked(request):
data = await request.post() data = await request.post()
text = data.get('text') text = data.get('text')
response_text = f'Вы ввели: {text}' response_text = f'Вы ввели: {text}'
print(response_text) print(response_text)
return Response(text=response_text) return Response(text=response_text)
Loading…
Cancel
Save