CGI-capable and portable HTTP web server in just 8 lines of code (and a whopping 16
if we include comments and blank lines).
As we’ll see later in this book, it’s also easy to build proprietary network servers with
low-level socket calls in Python, but the standard library provides canned implemen-
tations for many common server types, web based or otherwise. The socketserver
module, for instance, supports threaded and forking versions of TCP and UDP servers.
Third-party systems such as Twisted provide even more implementations. For serving
up web content, the standard library modules used in Example 1-32 provide what
we need.
Example 1-32. PP4E\Preview\webserver.py
"""
Implement an HTTP web server in Python that knows how to run server-side
CGI scripts coded in Python; serves files and scripts from current working
dir; Python scripts must be stored in webdir\cgi-bin or webdir\htbin;
"""
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.' # where your html files and cgi-bin script directory live
port = 80 # default http://localhost/, else use http://localhost:xxxx/
os.chdir(webdir) # run in HTML root dir
srvraddr = ("", port) # my hostname, portnumber
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever() # run as perpetual daemon
The classes this script uses assume that the HTML files to be served up reside in the
current working directory and that the CGI scripts to be run live in a cgi-bin or htbin
subdirectory there. We’re using a cgi-bin subdirectory for scripts, as suggested by the
filename of Example 1-31. Some web servers look at filename extensions to detect CGI
scripts; our script uses this subdirectory-based scheme instead.
To launch the server, simply run this script (in a console window, by an icon click, or
otherwise); it runs perpetually, waiting for requests to be submitted from browsers and
other clients. The server listens for requests on the machine on which it runs and on
the standard HTTP port number 80. To use this script to serve up other websites, either
launch it from the directory that contains your HTML files and a cgi-bin subdirectory
that contains your CGI scripts, or change its webdir variable to reflect the site’s root
directory (it will automatically change to that directory and serve files located there).
But where in cyberspace do you actually run the server script? If you look closely
enough, you’ll notice that the server name in the addresses of the prior section’s ex-
amples (near the top right of the browser after the http://)) is always localhost. To keep
this simple, I am running the web server on the same machine as the web browser;
that’s what the server name “localhost” (and the equivalent IP address “127.0.0.1”)
means. That is, the client and server machines are the same: the client (web browser)
56 | Chapter 1: A Sneak Preview