[Tutor] Passing Arguments to a Remote CGI Script
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 13 Sep 2002 23:52:59 -0700 (PDT)
On Fri, 13 Sep 2002 Jmllr891@cs.com wrote:
> I've been fooling around with Python and the web lately. I need to know,
> how would you pass arguments (such as a username and password) to a
> remote CGI script directly from within Python?
Hello!
We can pass information into a CGI in a few ways. The easiest would
probably be to pass it in as part of the "query string" --- as part of the
URL that starts off with a question mark.
For example, let's say that we had a CGI running on a server, like this:
###
"""test.cgi --- a small CGI program to show how one can pass parameters.
"""
import cgi
fs = cgi.FieldStorage()
print "Content-type: text/plain\n"
for key in fs.keys():
print "%s = %s" % (key, fs[key].value)
###
Simple enough --- this should just echo off any parameters we send to it.
Ok, with this, we can experiment a bit with passing parameters. If you
have a browser ready, try putting in the url of the cgi, and add to the
end of it... something like this:
?name=jmllr891&password=python
For example, the following url:
http://www.decrem.com/~dyoo/test.cgi?name=dyoo&password=tutor
runs the 'test.cgi' CGI script and passes those two parameters into the
CGI. (If you'ved noticed, lots of dynamic web sites, like amazon.com,
have weird URLs like this: that's the passing of parameters between your
browser and the CGI's on a server.)
So all our Python program needs to do is pack all our parameter arguments
in a string, and then use the 'urllib' url-handling module to send them
off. The urllib module has a fucntion called 'urllib.urlencode()' that
does most of the hard work:
###
import urllib
params = { 'language' : 'Python',
'url': 'http://python.org' }
encoded_params = urllib.urlencode(params)
response = urllib.urlopen('http://www.decrem.com/~dyoo/test.cgi?%s' %
encoded_params)
print "here's what the CGI sent back to us: ", response.read()
###
Please feel free to ask more questions; I think I rushed certain things,
so if anything's fuzzy, we can try concentrating on those things. I hope
this helps!