Re: cgi.py

Michael McLay (mclay@eeel.nist.gov)
Wed, 22 Jun 94 09:43:39 EDT

N.G.Smith writes:
> In article <9406211529.AA00645@acdc.eeel.nist.gov> mclay@eeel.nist.gov (Michael McLay) writes:
> >Thanks for the bug report. The fix also eliminated some ugly code. I've
> >incorporated your suggestion and attached the update.
> >
> >Michael
> >
> > nv = string.splitfields(name_value, '=')
> > name = nv[0]
> > value = urllib.unquote(nv[1])
> > if len(value):
> > if self.t.has_key (name):
> > self.t[name].append(value)
> > else:
> > self.t[name] = [value]
>
> I do not know whether it is legal to have a query string with the
> right hand side of the `=' empty, but if it is, this code will still
> break. My fix went something like this...

A query string on the rhs will be empty when a field is left blank in
an html form. The test for len(nv) == 2 will always be true since
Python will always return a two element list when splitting a
name/value pair on '='. I chose to only add name/value pairs to the
dictionary if a name had a values assigned. I could have added the
name and made the value None. This would have required testing the
value of a 'value' rather than testing for the existance of a name in
the dictionary. It was a design choice and I picked my approach based
on how I was using the forms at the time.

> nv = string.splitfields(name_value, '=')
> if len(nv) == 2:
> name = nv[0]
> value = urllib.unquote(nv[1])
> if self.t.has_key (name):
> self.t[name].append(value)
> else:
> self.t[name] = [value]
>
> But on second thoughts, this will simply not set the variable if the
> rhs is empty, whereas what it perhaps should do is set it to an empty
> string.

This approach did set the name in the dictionary to an empty string.
I picked the approach of not adding the name to the dictionary instead.

> Can anyone with more python experience than me offer a good
> solution?

With my approach, you can use tests for the existance of a key to
determine an action and you don't end up with value lists that are
cluttered with None values.

form = FormContent()

if form.has_key('foo'):
print 'has a foo key'

Using the alternative approach you would have:

if form.value('foo') == '':
print 'has a foo key'

If, as in the testpost.html example, more than one field may return
values for the same name, a list will be created and populated with
empty strings. My approach will not insert the empty strings into the
list.

Michael