[Tutor] Env Vars

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 3 Jul 2002 14:17:14 -0700 (PDT)


On Wed, 3 Jul 2002, Kyle Babich wrote:

> I copied and pasted exactly what you put and replaced the path to python.
> It says there is a syntax error at import HTMLgen.

Hi Kyle,


Ah!  That's probably a typo in the code: the block between the 'try:' and
the 'except:' needs to be indented.



> Also, is all of that really necessary just to print one environment
> variable?

If we just want to print the environmental variable, we can do this:

###
import os
print "Content-type: text/plain\n\n"
print "The server is running", os.name
###

and for simple stuff, this should be perfectly sufficient.




Lloyd was showing a "simple" example of using the HTMLgen module.
There's a admittedly some overhead in actually using the module itself,
but that overhead comes with an advantage: HTMLgen is taking care of
tricky details that CGI programmers can overlook if they're not careful.


Let's take a look at the brunt of the HTMLgen stuff:

> > ostext = HTMLgen.Text( "The server is running %s" % os.name)

The first line is constructing a chunk of text.  This may seem simple
enough to be silly:  why do we even need to process it with HTMLgen?

But then, HTMLgen is taking care of some details.  Specifically, it's
automatically HTML-quoting special characters like apostrophies and
less-than signs for us:

http://starship.python.net/crew/friedrich/HTMLgen/html/HTMLgen-Text.html

HTML doesn't allow certain characters in documents because, otherwise,
they could be mistaking for HTML tags!  So although it might be overkill
for something simple like printing out 'os.name', it becomes much more
useful when we use it in more involving scripts, where we get our data for
all sorts of places.



> > doc.append(ostext)
> > doc.write()

Note that HTMLgen does not automatically print stuff to screen, which also
may seem somewhat Useless: We insert it into the document 'doc', but we
have to call doc.write() to get it to actually print out to the user. Why
not just print 'ostext' out using a simple 'print' statement like this?

###
print ostext
###

and be done with it?


One reason for delaying the printing is because it's often efficient to
"buffer" our output and send it off in one go, instead of in little
chunks.  Buffering is a good thing for a few other reasons, and you'll
learn about them as you program more CGI's.

(One reason is that delaying output allows us to forwards and redirects
more easily, without worrying about what has been sent to the user's
browser window already.)



Also, HTMLgen is not just for CGI's: it can used in automatically
generating HTML documents to disk.  doc.write() can take in an optional
'filename' parameter:

http://starship.python.net/crew/friedrich/HTMLgen/html/index.html

so that the output is not to screen, but to a file.


Please feel free to ask more questions.  Hope this helps!