Why the Python BaseHttpServer server stops after execution?

204 views Asked by At

I am trying to develop application which will have a Python Webserver. Everything works as expected, but after executing the logic(by using do_GET and do_POST methods) the server just stops and a connection reset page is visible. Below is the screenshot of the page:

enter image description here

And below is the Python webserver code:

 from http.server import BaseHTTPRequestHandler, HTTPServer

 # HTTPRequestHandler class
 class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):

 # GET
 def do_GET(self):
    # Send response status code
    self.send_response(200)

    # Send headers
    self.send_header('Content-type','text/html')
    self.end_headers()
    file = "./some2.html"
    file2 = open(file,"r")
    # Write content as utf-8 data
    self.wfile.write(bytes(file2.read(), "utf8"))
    #return

 def do_POST(self):
    content_len = int(self.headers.get('content-length', 0))
    post_body = self.rfile.read(content_len)
    print(post_body)
    with open("rsmsg.txt","a") as f:
      f.write(str(post_body))
    print("Done storing file")  
    #return

 def run():
    print('starting server...')
    # Server settings
    server_address = ('192.168.10.151', 8083)
    httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
    print('running server...')
    httpd.serve_forever()

 run()

And below is the HTML code:

<html>
 <body> 
   <script>
     function getvalue(){
        value1 = document.getElementById("first").innerHTML
        value2 = document.getElementById("last").innerHTML
        return value1+value2
     }
   </script>    

   <form action="" method="post">
      First name:<br>
     <input id="first" type="text" name="firstname">
     <br>
     Last name:<br>
     <input id = "last" type="text" name="lastname">
     <br><br>
     <button type = "submit" onclick=getvalue()>Press it to store data on    server</button>
   </form> 

 </body>
</html>

After pressing button the data in the input id="first" and input id="last" will given to server. But after pressing why the The connection reset page is displayed? and how do I prevent it?

UPDATE After debugging I understood that in the JS in HTML code, the value1 and value2 are null but still I am getting data! but with field names. Example: firstname=Nick&lastname=A. I thought this might be the reason for the connection reset page hence updated the question.

Terminal Output The output seen on terminal

0

There are 0 answers