Passing arguments to python from URL

David M. Cooke cookedm+news at physics.mcmaster.ca
Tue Mar 22 21:52:55 EST 2005


Casey Bralla <Nobody at Nowhere.com> writes:

> I've got a python cgi-bin application which produces an apache web page.  I
> want to pass arguments to it on the URL line, but the parameters are not
> getting passed along to python properly.
>
> I've been using sys.argv to pick up command line arguments, and it works
> fine when I call the python program from the command line.  Unfortunately,
> when I pass data to the program from the URL, many of the parameters are
> being clobbered and **NOT** passed to python.
>
> For example:  "http://www.nobody.com/cgi-bin/program.py?sort=ascending" only
> passes the parameter "/usr/lib/cgi-bin/program.py".

This is expected.

> However, "http://www.nobody.com/cgi-bin/program.py?sort%20ascending" passes
> a 2-place tuple of ("/usr/lib/cgi-bin/program.py", "sort
> ascending").

I don't know why this actually works, it's not (AFAIK) defined behaviour.

> Somehow, adding the "=" in the argument list prevents **ANY** parameters
> from being passed to python.  I could re-write the python program to work
> around this, but I sure would like to understand it first.

You're going to have to rewrite. CGI scripts get their arguments
passed to them through the environment, not on the command line.
QUERY_STRING, for instance, will hold the query string (the stuff
after the ?).

Use Python's cgi module to make things easier on yourself; the
documentation has a good overview:
http://www.python.org/doc/2.4/lib/module-cgi.html

In this case, your script would look something like this:

import cgi
form = cgi.FieldStorage()
if form.getvalue('sort') == 'ascending':
    ... sort in ascending order ...

etc.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list