[Tutor] Is Python powerful enough for this?
Kirby Urner
urnerk@qwest.net
Fri, 31 Aug 2001 10:58:37 -0400
The POST method itself creates the urlencoded string and
sets the environment variable CONTENT_LENGTH to the
length of this string. The string itself is sent via standard
input, not as part of the URL itself, as in GET.
The job, then, is to get the name/value pairs back out from
the string, which is something the cgi module will do for you.
Others have mentioned FieldStorage(). There's also cgi.parse().
Here's a cgi script set up to handle the example HTML you
posted:
==============================
#!/usr/local/bin/python
import cgi
import sys
import traceback
sys.stderr = sys.stdout
print "Content-Type: text/html\n"
try:
print """
<html>
<head>
<title>Feedback</title>
</head>\n<body>"""
vars = cgi.parse()
for i in vars.keys(): # or just 'in vars' in 2.2+
print "<p>Name: %s Value: %s</p>" % (i,vars[i])
print """
</body>
</html>"""
except:
print "\n\n<PRE>"
traceback.print_exc()
print "\n</PRE>"
ÆÆÆ
==============================
Note the trick of putting debugging code at the end. This helps you
initially when trying to figure out why a script fails. You can strip
this stuff out later (see what happens if you divide by 0 in the
try block -- the browser will give you Python's informative error
message instead of some useless "internal error" message).
Minor footnote: dictionaries before Python 2.2 weren't iterable
directly; you had to go for i in mydict.keys(): But now dictionaries
are directly iterable, so you can just go for i in mydict:
Kirby
On Thursday 30 August 2001 08:03, A wrote:
> Hi,
> I have some webpages that contain FORMS. Each form has input
> fields and also some hidden fields.
> How can I easily get urlencoded string from all these fields
> like
> Key1=Value1&Key2=Value2&Key3=Value3
>
> For example:
> I have a following web page
> <html>
>
> <head>
> </head>
> <body>
> <form method="POST" action="c.cgi">
> <p><input type="text" name="T1" size="20"></p>
> <p><input type="checkbox" name="C1" value="ON"></p>
> <p><textarea rows="2" name="S1" cols="20"></textarea></p>
> <p><input type="submit" value="Submit" name="B1"><input
> type="reset" value="Reset" name="B2"></p>
> </form>
> </body>
> </html>
>
> From the above
> I would like to receive
> T1=&S1=&C1=&B1=Submit
>
>
> Thank you for help.
> Ladislav
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor