Web Python: URL Query String How-To

One thing many websites use is the query string in urls, that let you pass variables from page to page, and to your script. These are normally written as website.com/script.py?name=bob where name would equal the variable name and bob would be the value. So how do you get these names and values?
First lets start off with a blank python cgi script:

#!/usr/bin/env python

Now lets import the cgi module on the next line:

#!/usr/bin/env python

import cgi

Now lets create a query variable using the FieldStorage() class, which contains the query variables as well as variables from forms on the calling page.

#!/usr/bin/env python

import cgi
query=cgi.FieldStorage()

Now we can use getvalue() on the query variable, save that result into a variable, and print out the result:

#!/usr/bin/env python

import cgi
query=cgi.FieldStorage()
name=query.getvalue('name')
print "Content-type: text/html\n\n"
print name

Now save your script as "query.py" and upload it to the cgi-bin directory, make sure to chmod it, and test it out by going to: yoursite.com/cgi-bin/query.py?name=bob

If "bob" shows up in your browser window, everything worked!

Now lets try to loop through the keys so we can display all the variables contained in FieldStorage()

for key in query.keys():
  print key+"="+query.getvalue(key)+"<br>"

Now if you upload and run yoursite.com/cgi-bin/query.py?name=bob&age=32 you should see the output:
name=bob
age=32