[Tutor] returning to my memberlister script

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 1 Sep 2002 13:49:49 -0700 (PDT)


On Sat, 31 Aug 2002, Kirk Bailey wrote:

> OK, this is getting frustrating. I am reading the actual source text for
> cgi.py, and sure enough, the damn thing returns a dictionary. This
> script should be working, and it howls like a wolf with a full moon.
> Which means I am doing something wrong, but I am not catching it. Anyone
> want to look at this and adjust my headspace and timing please? This
> apprentice requests correction.

Hi Kirk,

Let's look at the error message and see if it can give us clues as to
what's going on:


> > SyntaxError: invalid syntax
> > [Thu Aug 29 00:26:38 2002] [error] [client 63.208.207.252] Premature end of script headers: /www/www.tinylist.org/cgi-bin/TLmemberlister.py
> > Traceback (innermost last):
> >   File "/www/www.tinylist.org/cgi-bin/TLmemberlister.py", line 126, in ?
> >     print 'listname='+mylist+'<P>'
> > TypeError: __add__ nor __radd__ defined for these operands


Hmmm... It looks like the statement:

    print 'listname='+mylist+'<P>'

has a bug in it; Python is complaining that something on this line doesn't
like to be added together.

My assumption right now is that 'mylist' is not a string: that's the only
thing I can think of that will cause Python to make that TypeError
complaint.

What is 'mylist'?

    mylist = form["listname"]                       # listname,


Ah!  This needs to be replaced with:

    mylist = form['listname'].value


The reason is because the FieldStorage object isn't quite a dictionary:
although it provides a dictionary-like interface, we need to go through an
extra step to get the 'value' of a parameter.

Why is FieldStorage designed in this way?  Isn't it horribly indirect?


Yes, but that's because the values returned by FieldStorage are a bit
chunky: we can get either a single value, multiple values, or even a
file-like object!  Think of uploading a huge file in a CGI script: if
someone sends us a HUGE file, we may want to read through it a line at a
time, rather than all at once.  The FieldStorage module allows us to check
for this situation like this:

###
if form['data'].file:
    f = form['data'].file
    for line in f.xreadlines():
        ...
###

We may want to be able to detect these different situations, so that's why
there's a bit of indirectness in the FieldStorage object.

The documentation does try to explain this, but it takes a while to see
what it's actually talking about.  *grin* See:

    http://www.python.org/doc/lib/node295.html

for more details.


Good luck!