[Tutor] CGI and Better Programming Practice

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 23 Feb 2001 01:37:50 -0800 (PST)

On Thu, 22 Feb 2001, Jason Drake wrote:

> These things said and a cold Heineken at my side, I would post the
> code thus far, but would rather not stick so much bad code into one
> document :) Instead I'll post the offensive code at
> www.lowerstandard.com/frik/thecode.html by way of links to .txt
> documents for the curious to peruse as well as links to the actual
> working versions. Give me 5-10 minutes and it'll be there.

I've looked at some of your code; one improvement you can make is to use
Python's string interpolation feature.  For example, the following code:

print "<html>"
print "<head>"
print "<title>"
print "Your Info"
print "</title>"
print "</head>"
print "<body>"
print "You gave the following information:"
print "<br>"
print "<br>"
print form["name"].value
print "<br>"
print form["age"].value
print "<br>"
print form["class"].value
print "<br>"
print "<br>"
print "or... "
print output

can be written like this (with some formatting liberties...):

template = """
<head><title>Your Info</title></head>
You gave the following information:
print output % { 'name' : form['name'].value,
                 'age' : form['age'].value,
                 'class': form['class'].value,
                 'output': output }

(note: I have not tested this code yet; it might contain bugs.)

When we apply the string interpolation operator '%' to our template,
Python will substitute anything that looks like '%(some_key_name)s' with
the value of the dictionary we're passing in.

What's nice about this interpolation method is that our template looks
more like the HTML that its representing.  It's also neat because we could
conceivable read off that template from a different file if we wanted to;
it would be a snap to make changes to the look of the template.

Hope this helps!