We have used a basic HTTP server setup that can handle CGI requests. Python 3 provides these interfaces in the http.server module. Python 2 had the modules BaseHTTPServer and CGIHTTPserver to offer the same, which were merged in Python into http.server.
The handler is configured to use the /cgi-bin path to launch the CGI scripts. No other path can be used to run the CGI scripts.
The HTML feedback form located on 15_7_send_feedback.html shows a very basic HTML form containing the following code:
<html> <body> <form action="/cgi-bin/15_7_get_feedback.py" method="post"> Name: <input type="text" name="Name"> <br /> Comment: <input type="text" name="Comment" /> <input type="submit" value="Submit" /> </form> </body> </html>
Note that the form method is POST and action is set to the /cgi-bin/15_7_get_feedback.py file. The contents of this file are as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 5 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. #!/usr/bin/python # Import modules for CGI handling import cgi import cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields name = form.getvalue('Name') comment = form.getvalue('Comment') print ("Content-type:text/html ") print ("<html>") print ("<head>") print ("<title>CGI Program Example </title>") print ("</head>") print ("<body>") print ("<h2> %s sends a comment: %s</h2>" % (name, comment)) print ("</body>") print ("</html>")
In this CGI script, the FieldStorage() method is called from cgilib. This returns a form object to process the HTML form inputs. Two inputs are parsed here (name and comment) using the getvalue() method. Finally, the script acknowledges the user input by echoing a line back saying that the user x has sent a comment.
If you encounter any errors as follows:
127.0.0.1 - - [22/Jun/2017 00:03:51] code 403, message CGI script is not executable ('/cgi-bin/15_7_get_feedback.py')
Make it executable. It can be done by following the following command in Linux:
$ chmod a+x cgi-bin/15_7_get_feedback.py
Once it is made executable, you can rerun the program without any issue.