HTML+Python text input [closed]
Want to improve this question? Update the question so that it it fit into the theme of Stack Overflow in Russian.
Closed 8 days ago.
Improve the questionI have a website in html. There is also a bot on pythom (question-answer using print and input). I want that through the input line on the site, the text from python (print or input) is imported to the site and I wrote the answer below, so that it would be visible that the user wrote and that python answered me. Are there any ways to implement this? This should look similar to the bots from aiproject.ru I will be very grateful for your help
1 answers
Here is the working code:
Python
# WS Сервер (базовый пример)
import asyncio # Библиотека стандартной архитектуры асинхронного ввода - вывода в Python
import websockets
import pymysql
import json
import datetime
async def hello(websocket, path): # На стороне сервера websocket выполняет
# сопрограмму обработчика hello один раз для каждого соединения
ask = await websocket.recv()
ask = json.loads(ask)
if ask["comm"] == 'get':
print('Я ПОЛУЧИЛ КОМАНДУ!')
await websocket.send('Ну, здорова, Странник!')
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
# Закрывает соединение после возврата
# async/await -(специальный синтаксис для работы с промисами)
# Промис- это объект,
# представляющий возможное завершение передачи или сбой асинхронной операции
# В Python async гарантирует, что функция вернет промис и обернет в него не промисы.
HTML + JS(All in one)
<!DOCTYPE html>
<html>
<head>
<title>WebSocket demo</title>
</head>
<body>
<button id="get">Получить данные</button>
<script>
function get_readers(){
var ws = new WebSocket("ws://127.0.0.1:8765/"),
messages = document.createElement('ul');
ws.onopen = function () {
let data = {
comm: 'get'
};
let json = JSON.stringify(data);
ws.send(json);
};
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode(event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
};
document.getElementById("get").addEventListener("click", get_readers)
</script>
</body>
</html>
Here is a working example. You just need to finish input
in HTML and pass it through JSON
(there is a line get
in html, add output
to it, and in python, too, through JSON
, extract the input, and then if else
).
PS If you have any questions, write to VK(the link can be found in your account ;))