develop #3

Merged
Kirill merged 12 commits from develop into main 2 years ago
  1. 1
      demo/func/__init__.py
  2. 21
      demo/func/secondary_functions.py
  3. 6
      demo/routes.py
  4. 40
      demo/templates/index.html
  5. 92
      demo/templates/index_2.html
  6. 1
      demo/views/__init__.py
  7. 26
      demo/views/frontend.py
  8. 1
      entry.py

@ -0,0 +1 @@
from . import secondary_functions

@ -0,0 +1,21 @@
import time
import asyncio
from aiohttp.web_ws import WebSocketResponse
async def time_response(ws: WebSocketResponse, delay: int = 60):
while True:
new_time: time.gmtime = time.gmtime(time.time())
hour = new_time.tm_hour + 3
if hour >= 24:
hour = hour - 24
minutes = new_time.tm_min
if minutes < 10:
minutes = f'0{minutes}'
result_response = f'Время: {hour}:{minutes}'
try:
await ws.send_str(result_response)
await asyncio.sleep(delay)
except ConnectionResetError:
break

@ -3,5 +3,9 @@ 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,11 +10,15 @@
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;
@ -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
event.preventDefault(); // Предотвращаем отправку формы по умолчанию .getElementById("myForm")
.addEventListener("submit", async function (event) {
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,38 @@
import asyncio
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
from ..func import secondary_functions
@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(secondary_functions.time_response(ws, delay=60))
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
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)

Loading…
Cancel
Save