We placed our Python CGI script inside a cgi-bin/ subdirectory and then visited the HTML page that contains the feedback form. Upon submitting this form, our web server will send the form data to the CGI script, and we'll see the output produced by this script.
Listing 5.7 shows us how the Python web server supports CGI:
#!/usr/bin/env python # Python Network Programming Cookbook -- Chapter - 5 # This program requires Python 3.5.2 or any later version # It may run on any other version with/without modifications. # # Follow the comments inline to make it run on Python 2.7.x. import os import cgi import argparse import http.server # Comment out the above line and uncomment the below for Python 2.7.x. #import BaseHTTPServer # Uncomment the below line for Python 2.7.x. #import CGIHTTPServer import cgitb cgitb.enable() ## enable CGI error reporting def web_server(port): server = http.server.HTTPServer # Comment out the above line and uncomment the below for Python 2.7.x. #server = BaseHTTPServer.HTTPServer handler = http.server.CGIHTTPRequestHandler #RequestsHandler # Comment out the above line and uncomment the below for Python 2.7.x. #handler = CGIHTTPServer.CGIHTTPRequestHandler #RequestsHandler server_address = ("", port) handler.cgi_directories = ["/cgi-bin", ] httpd = server(server_address, handler) print ("Starting web server with CGI support on port: %s ..." %port) httpd.serve_forever() if __name__ == '__main__': parser = argparse.ArgumentParser(description='CGI Server Example') parser.add_argument('--port', action="store",
dest="port", type=int, required=True) given_args = parser.parse_args() web_server(given_args.port)
The following screenshot shows a CGI enabled web server serving contents:
If you run this recipe, you will see the following output:
$ python 5_7_cgi_server.py --port=8800 Starting web server with CGI support on port: 8800 ... localhost - - [19/May/2013 18:40:22] "GET / HTTP/1.1" 200 -
Now, you need to visit http://localhost:8800/5_7_send_feedback.html from your browser.
You will see an input form. We assume that you provide the following input to this form:
Name: User1 Comment: Comment1
The following screenshot shows the entering user comment in a web form:
Then, your browser will be redirected to http://localhost:8800/cgi-bin/5_7_get_feedback.py where you can see the following output: