Home > other >  How to get form value using python sockets?
How to get form value using python sockets?

Time:11-03

I created a simple website with forms, i want to get the input enterd on id 'message'
my code:

website.py

import socket

SERVER_HOST = '127.0.0.1'
SERVER_PORT = 8000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
print('Listening on port %s ...' % SERVER_PORT)
#sender
while True:    
    client_connection, client_address = server_socket.accept()

    request = client_connection.recv(1024).decode()
    print(request)
    with open('form.html', 'r')as f:
        file=f.read()
    response = 'HTTP/1.0 200 OK\n\n' file
    client_connection.sendall(response.encode())
    client_connection.close()
server_socket.close()

form.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>form</title>
  </head>
  <body>
    <form action="/" method="get" accept-charset="utf-8">
      <input type="text" name="message" id="message" value="" />
      <input type="submit" name="submit" id="submit" value="submit" />
    </form>
  </body>
</html>

can you help me to print the input enterd on id 'message' ?
using only socket or other internal libraries.

CodePudding user response:

There is multiple way to do it :

  1. Use XMLHttpRequest which make you able to do web request. This can be used to get a page. Example:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText); // good result !
    }
};
xmlhttp.open("GET", "http://my.url/example", true);
xmlhttp.send();

Then, in you HTML page you just should return the result.

  1. Use WebSocket

Server side

You have to use something that can support WebSocket. It's different from "basic" socket, because it will pass with HTTP protocol (but on 8000 port).

To do it, you should use Python Websocket. You can install it with pip install websocket-server.

This is my code:

import logging
from websocket_server import WebsocketServer

def new_client(client, server):
   print("New client !")

def received_msg(client, server, message):
   print("New message:", message)

server = WebsocketServer(host='127.0.0.1', port=8000, loglevel=logging.INFO)
server.set_fn_new_client(new_client)
server.set_fn_message_received(received_msg)
server.run_forever()

Client side

Here is the HTML part with the websocket utilisation :

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>form</title>
  </head>
  <body>
    <form action="/" method="get" accept-charset="utf-8">
      <input type="text" name="message" id="message" value="" />
    </form>
    <button onclick="run()">Run</button>
  </body>
  <script type="text/javascript">
    var socket = new WebSocket("ws://localhost:8000");
    socket.onopen = function (event) {
      console.log("opened");
      socket.send("Opened !");
    };
    function run() {
      socket.send(JSON.stringify({ "message": document.getElementById("message").value }));
    }

  </script>
</html>

Finally

When you show HTML page, enter a message and click on "Run" :

INFO:websocket_server.websocket_server:Listening on port 8000 for clients..
INFO:websocket_server.websocket_server:Starting WebsocketServer on main thread.
New client !
New message: Opened !
New message: {"message":"value"}
  • Related