Compare commits

...

5 Commits

  1. 7
      demo/routes.py
  2. 56
      demo/templates/index.html
  3. 92
      demo/templates/index_2.html
  4. 1
      demo/views/__init__.py
  5. 41
      demo/views/frontend.py
  6. 1
      entry.py

@ -3,5 +3,10 @@ import aiohttp
def setup_routes(app): def setup_routes(app):
app.router.add_routes([aiohttp.web.get('/', frontend.index), aiohttp.web.post('/submit', frontend.button_clicked)]) app.router.add_routes([aiohttp.web.get('/index.html', frontend.index),
aiohttp.web.post('/submit', frontend.button_clicked),
aiohttp.web.get('/index_2.html', frontend.index_2),
aiohttp.web.get('/ws', frontend.websocket_handler)
]
)

@ -10,31 +10,35 @@
body { body {
min-height: 100vh; min-height: 100vh;
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 35%, rgba(0,212,255,1) 100%) background: linear-gradient(
90deg,
rgba(2, 0, 36, 1) 0%,
rgba(9, 9, 121, 1) 35%,
rgba(0, 212, 255, 1) 100%
);
} }
h1{ h1 {
color: white; color: white;
} }
p{ p {
color:white; color: white;
} }
.container{ .container {
margin-left: 20vw; margin-left: 20vw;
} }
#submit{ #submit {
margin-top: 20px; margin-top: 20px;
border-radius: 10px; border-radius: 10px;
height: 50px; height: 50px;
width:50vw; width: 50vw;
color:black; color: black;
} }
#inputText{ #inputText {
border-radius: 10px; border-radius: 10px;
height: 30px; height: 30px;
width: 49.5vw; width: 49.5vw;
} }
.container_result{ .container_result {
margin-top: 20px; margin-top: 20px;
min-height: 50px; min-height: 50px;
text-align: center; text-align: center;
@ -43,8 +47,6 @@
border-radius: 5px; border-radius: 5px;
background-color: grey; background-color: grey;
} }
</style> </style>
</head> </head>
<body> <body>
@ -53,35 +55,41 @@
<div id="root"> <div id="root">
<div class="form"> <div class="form">
<form id="myForm"> <form id="myForm">
<input type="text" id="inputText" placeholder="Введите текст"> <input type="text" id="inputText" placeholder="Введите текст" />
<div class="form__button"><button id='submit'>Отправить</button></div> <div class="form__button">
<button id="submit">Отправить</button>
</div>
</form> </form>
<div class="container_result"> <div class="container_result">
<p id="response"></p> <p id="response"></p>
</div> </div>
<div>
<a href="/index_2.html">Перейти на страницу 2</a>
</div>
</div> </div>
</div> </div>
</div> </div>
</body> </body>
<script> <script>
document.getElementById('myForm').addEventListener('submit', async function(event) { document
.getElementById("myForm")
.addEventListener("submit", async function (event) {
event.preventDefault(); // Предотвращаем отправку формы по умолчанию event.preventDefault(); // Предотвращаем отправку формы по умолчанию
const inputText = document.getElementById('inputText').value; const inputText = document.getElementById("inputText").value;
const response = await fetch('/submit', { const response = await fetch("/submit", {
method: 'POST', method: "POST",
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded' "Content-Type": "application/x-www-form-urlencoded",
}, },
body: new URLSearchParams({ body: new URLSearchParams({
'text': inputText text: inputText,
}) }),
}); });
const responseText = await response.text(); const responseText = await response.text();
document.getElementById('response').innerText = responseText; document.getElementById("response").innerText = responseText;
}); });
</script> </script>
</html> </html>

@ -0,0 +1,92 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Знакомство с aiohttp</title>
<style>
html {
font-family: Verdana, "sans-serif";
}
body {
min-height: 100vh;
background: linear-gradient(
90deg,
rgba(2, 0, 36, 1) 0%,
rgba(9, 9, 121, 1) 35%,
rgba(0, 212, 255, 1) 100%
);
}
h1,
p {
color: white;
}
.time_block,
.output_block {
border: 2px solid white;
border-radius: 5px;
margin: 10px;
padding: 10px;
height: 50px;
width: 300px;
}
.message_form {
margin: 10px;
}
</style>
</head>
<body>
<header>
<h1>Дата и время</h1>
</header>
<main>
<div class="time_block">
<p id="time"></p>
</div>
<div class="message_form">
<form id="myForm2">
<input
type="text"
name="message_text_user"
placeholder="Введите текст"
/>
<input type="button" name="submit_message" value="Отправить" />
</form>
</div>
<div class="output_block">
<p id="output_message" class="output"></p>
</div>
</main>
<script>
const messageTime = document.getElementById("time");
const messageInput = document.querySelector("[name=message_text_user]");
const messageOtput = document.getElementById("output_message");
const sendMessage = document.querySelector("[name=submit_message]");
let websocketClient = new WebSocket("ws://127.0.0.1:8080/ws");
websocketClient.onopen = () => {
console.log("Client connected!");
sendMessage.onclick = () => {
console.log("1");
websocketClient.send(messageInput.value);
messageInput.value = "";
};
};
websocketClient.onmessage = (message) => {
if (message.data.includes("Время: ")) {
if (typeof messageTime.textContent !== "undefined") {
messageTime.textContent = message.data;
} else {
messageTime.innerText = message.data;
}
} else {
if (typeof messageOtput.textContent !== "undefined") {
messageOtput.textContent = message.data;
} else {
messageOtput.innerText = message.data;
}
}
};
</script>
</body>
</html>

@ -1 +1,2 @@
from . import frontend from . import frontend

@ -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)

@ -6,3 +6,4 @@ app = create_app()
if __name__ == '__main__': if __name__ == '__main__':
aiohttp.web.run_app(app) aiohttp.web.run_app(app)
# Добавить 2 страничку, подключить ws, отправлял текущие время раз в минуту. Ну и также отвечать на собщения.

Loading…
Cancel
Save