parent
aaf608d2d2
commit
c95a7e4c58
@ -1,16 +1,51 @@ |
|||||||
import aiohttp |
import aiohttp |
||||||
|
from aiohttp import WSMsgType |
||||||
|
from aiohttp.web_response import Response |
||||||
|
from aiohttp.web_ws import WebSocketResponse |
||||||
from aiohttp_jinja2 import template |
from aiohttp_jinja2 import template |
||||||
|
import time |
||||||
|
import asyncio |
||||||
|
|
||||||
|
async def time_response(ws: WebSocketResponse, delay: int = 60): |
||||||
|
while True: |
||||||
|
new_time: time.gmtime = time.gmtime(time.time()) |
||||||
|
time_response = f'Время: {new_time.tm_hour + 3}:{new_time.tm_min} Задержка: {delay}' |
||||||
|
try: |
||||||
|
await ws.send_str(time_response) |
||||||
|
await asyncio.sleep(delay) |
||||||
|
except ConnectionResetError: |
||||||
|
await asyncio.sleep(delay) |
||||||
@template('index.html') |
@template('index.html') |
||||||
async def index(request): |
async def index(request): |
||||||
return {} |
return {} |
||||||
|
|
||||||
|
@template('index_2.html') |
||||||
|
async def index_2(request): |
||||||
|
return {} |
||||||
|
|
||||||
|
|
||||||
|
async def websocket_handler(request): |
||||||
|
ws: WebSocketResponse = WebSocketResponse() |
||||||
|
await ws.prepare(request) |
||||||
|
asyncio.create_task(time_response(ws)) |
||||||
|
async for msg in ws: |
||||||
|
|
||||||
|
if msg.type == aiohttp.WSMsgType.TEXT: |
||||||
|
|
||||||
|
if msg.data == 'close': |
||||||
|
await ws.close() |
||||||
|
else: |
||||||
|
await ws.send_str(f'Вы послали: {msg.data}') |
||||||
|
elif msg.type == WSMsgType.ERROR: |
||||||
|
print('ws connection closed with exception %s' % |
||||||
|
ws.exception()) |
||||||
|
|
||||||
|
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 aiohttp.web.Response(text=response_text) |
return Response(text=response_text) |
Loading…
Reference in new issue