A First CGI Script
The HTML file we saw in the prior section is just that—an HTML file, not a CGI script.
When referenced by a browser, the remote web server simply sends back the file’s text
to produce a new page in the browser. To illustrate the nature of CGI scripts, let’s
recode the example as a Python CGI program, as shown in Example 15-3.
Example 15-3. PP4E\Internet\Web\cgi-bin\tutor0.py
#!/usr/bin/python
"""
runs on the server, prints HTML to create a new page;
url=http://localhost/cgi-bin/tutor0.py
"""
print('Content-type: text/html\n')
print('
print('
A First CGI Script
')print('
Hello, CGI World!
')This file, tutor0.py, makes the same sort of page as Example 15-2 if you point your
browser at it—simply replace .html with .py in the URL, and add the cgi-bin subdir-
ectory name to the path to yield its address to enter in your browser’s address field,
http://localhost/cgi-bin/tutor0.py.
But this time it’s a very different kind of animal—it is an executable program that is run
on the server in response to your access request. It’s also a completely legal Python
program, in which the page’s HTML is printed dynamically, instead of being precoded
in a static file. In fact, little is CGI-specific about this Python program; if run from the
system command line, it simply prints HTML instead of generating a browser page:
C:\...\PP4E\Internet\Web\cgi-bin> python tutor0.py
Content-type: text/html
<TITLE>CGI 101</TITLE>
<H1>A First CGI Script</H1>
<P>Hello, CGI World!</P>
When run by the HTTP server program on a web server machine, however, the standard
output stream is tied to a socket read by the browser on the client machine. In this
context, all the output is sent across the Internet to your web browser. As such, it must
be formatted per the browser’s expectations.
In particular, when the script’s output reaches your browser, the first printed line is
interpreted as a header, describing the text that follows. There can be more than one
header line in the printed response, but there must always be a blank line between the
headers and the start of the HTML code (or other data). As we’ll see later, “cookie”
state retention directives show up in the header area as well, prior to the blank line.
In this script, the first header line tells the browser that the rest of the transmission is
HTML text (text/html), and the newline character (\n) at the end of the first print call
Climbing the CGI Learning Curve| 1141