#python #button #webserver
#python #кнопка #веб-сервер
Вопрос:
Я не смог найти ответ на этот простой вопрос python. Как изменить содержимое веб-страницы нажатием кнопки с помощью простого веб-сервера python. Вот мой урезанный код:
from http.server import BaseHTTPRequestHandler, HTTPServer
html = """<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>Test<p><button>Update</button></body></html>"""
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes(html, "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer(("192.168.1.197",1234), MyServer)
print("Started")
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
Ответ №1:
Нашел большую часть ответа на https://tutorialedge.net/python/python-socket-io-tutorial /
Но также см. Это об использовании сокетов: https://blogs.windows.com/windowsdeveloper/2016/03/14/when-to-use-a-http-call-instead-of-a-websocket-or-http-2-0/
Мой тестовый HTML:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<p id="mydoc">Hello</p>
<button onClick="sendMsg()">Update</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
const socket = io("http://localhost:8080");
function sendMsg() { socket.emit("message", "HELLO WORLD");}
socket.on("message", function(data) { document.getElementById("mydoc").textContent = "There"; });
</script>
</body>
</html>
Комментарии:
1. Я все равно хотел бы знать, как это сделать без сокетов.