[Tutor] Help with a cgi example
Justin Heath
justin at unixremedies.com
Fri Aug 22 11:22:33 EDT 2003
All,
I am currently working thru some of the cgi examples in "Programming
Python". I am stuck on how one of the examples works. Here is the example:
#!/usr/bin/python
import cgi, sys, string
form = cgi.FieldStorage( )
print "Content-type: text/html"
html = """
<TITLE>test5.cgi</TITLE>
<H1>Greetings</H1>
<HR>
<H4>Your name is %(name)s</H4>
<H4>You wear rather %(shoesize)s shoes</H4>
<H4>Your current job: %(job)s</H4>
<H4>You program in %(language)s</H4>
<H4>You also said:</H4>
<P>%(comment)s</P>
<HR>"""
data = {}
for field in ['name', 'shoesize', 'job', 'language', 'comment']:
if not form.has_key(field):
data[field] = '(unknown)'
else:
if type(form[field]) != type([]):
data[field] = form[field].value
else:
values = map(lambda x: x.value, form[field])
data[field] = string.join(values, ' and ')
print html % data
I am confused on the 'values = map(lambda x: x.value, form[field])'
line. I do not understand exactly what is happeing here. I believe I
understand that he is applying the lambda to every item in form[field]
by using map. However, I dont seem to understand what the lambda is
doing. I thought it was doing the same thing as 'form[field].value', but
I appear to be wrong since when I try this manually I get an error
stating that form[field] does not have a 'value' attribute.
I am not sure if anyone will need this for context but I have also
pasted the html form example here:
<HTML><BODY>
<TITLE>CGI 101</TITLE>
<H1>Common input devices</H1>
<HR>
<FORM method=POST action="test5.cgi">
<H3>Please complete the following form and click Send</H3>
<P><TABLE>
<TR>
<TH align=right>Name:
<TD><input type=text name=name>
<TR>
<TH align=right>Shoe size:
<TD><table>
<td><input type=radio name=shoesize value=small>Small
<td><input type=radio name=shoesize value=medium>Medium
<td><input type=radio name=shoesize value=large>Large
</table>
<TR>
<TH align=right>Occupation:
<TD><select name=job>
<option>Developer
<option>Manager
<option>Student
<option>Evangelist
<option>Other
</select>
<TR>
<TH align=right>Political affiliations:
<TD><table>
<td><input type=checkbox name=language value=Python>Pythonista
<td><input type=checkbox name=language value=Perl>Perlmonger
<td><input type=checkbox name=language value=Tcl>Tcler
</table>
<TR>
<TH align=right>Comments:
<TD><textarea name=comment cols=30 rows=2>Enter text here</textarea>
<TR>
<TD colspan=2 align=center>
<input type=submit value="Send">
</TABLE>
</FORM>
<HR>
</BODY></HTML>
Thanks,
Justin
More information about the Tutor
mailing list