showfields.py

Download: source file

CGI information may be passed through the URL as a query string, an ampersand (&) delimited set of "key=value" pairs. The query string starts after the question mark (?), as shown in the following example.

  https://johnloomis.org/python/showfields.py?animal=lion&fruit=apple&bird=robin
The query string encodes the control characters, such as the ampersand and equal sign and special characters such as the space. The cgi.FieldStorage() method unencodes these characters.

See Using the CGI Module for more information.

The following script uses the cgi module to parse the query string and generate a table of name/value pairs.


01: #!/usr/bin/python
02: import cgi, cgitb, os, sys
03: cgitb.enable(); # formats errors in HTML
04: 
05: sys.stderr = sys.stdout
06: print "Content-type: text/html"
07: print
08: print """<html>
09: <head><title>Show fields from CGI query string</title></head>
10: <body>"""
11: 
12: query = os.environ.get('QUERY_STRING')
13: if query: print "<p>QUERY_STRING:&nbsp&nbsp; <tt><font color=#FF00FF>", cgi.escape(query), "</font></tt>"
14: 
15: print """<p><table border>
16: <tr><th>Name<th>Value"""
17: 
18: form = cgi.FieldStorage()
19: 
20: for field in form.keys():
21:     print "<tr><td>%s<td>%s" % (field, form[field].value)
22: 
23: print "</table>"
24: print "</body></html>"


Results

The following link shows the output from the above script:


https://johnloomis.org/python/showfields.py?animal=lion&fruit=apple&bird=robin

You should get the following output:


QUERY_STRING:   animal=lion&fruit=apple&bird=robin

NameValue
animallion
fruitapple
birdrobin


Maintained by John Loomis, updated Sun Feb 10 22:59:20 2008