"""
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.' # where your HTML files and cgi-bin script directory live
port = 80 # http://servername/ if 80, else use http://servername:xxxx/
if len(sys.argv) > 1: webdir = sys.argv[1] # command-line args
if len(sys.argv) > 2: port = int(sys.argv[2]) # else default ., 80
print('webdir "%s", port %s' % (webdir, port))
os.chdir(webdir) # run in HTML root dir
srvraddr = ('', port) # my hostname, portnumber
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever() # serve clients till exit
To start the server to run this chapter’s examples, simply run this script from the di-
rectory the script’s file is located in, with no command-line arguments. For instance,
from a DOS command line:
C:\...\PP4E\Internet\Web> webserver.py
webdir ".", port 80
On Windows, you can simply click its icon and keep the console window open, or
launch it from a DOS command prompt. On Unix it can be run from a command line
in the background, or in its own terminal window. Some platforms may also require
you to have administrator privileges to run servers on reserved ports, such as the Web’s
port 80; if this includes your machine, either run the server with the required permis-
sions, or run on an alternate port number (more on port numbers later in this chapter).
By default, while running locally this way, the script serves up HTML pages requested
on “localhost” from the directory it lives in or is launched from, and runs Python CGI
scripts from the cgi-bin subdirectory located there; change its webdir variable or pass
in a command-line argument to point it to a different directory. Because of this struc-
ture, in the examples distribution HTML files are in the same directory as the web server
script and CGI scripts are located in the cgi-bin subdirectory. In other words, to visit
web pages and run scripts, we’ll be using URLs of these forms, respectively:
http://localhost/somepage.html
http://localhost/cgi-bin/somescript.py
Both map to the directory that contains the web server script (PP4E\Internet\Web) by
default. Again, to run the examples on a different server machine of your own, simply
replace the “localhost” and “localhost/cgi-bin” parts of these addresses with your server
name and directory path details (more on URLs later in this chapter); with this address
change the examples work the same, but requests are routed across a network to the
server, instead of being routed between programs running on the same local machine.
The server in Example 15-1 is by no means a production-grade web server, but it can
be used to experiment with this book’s examples and is viable as a way to test your CGI
1132 | Chapter 15: Server-Side Scripting