[Tutor] CGI Tutorial

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jun 28 00:51:24 CEST 2005



On Mon, 27 Jun 2005, Gooch, John wrote:

> Are there any tutorials on the Python CGI module? I think I found enough
> fragments to get form data, but I need a way for the Python script to
> tell whether it is being run in a web server environment or from the
> command line.

> What I am thinking is testing for an environment variable
> that only exists in the CGI environment, but not in a command shell.

Hi John,

According to the CGI specification here:

    http://hoohoo.ncsa.uiuc.edu/cgi/
    http://hoohoo.ncsa.uiuc.edu/cgi/env.html

the program should expect to see a few environmental variables.  One
popular environmental variable that's used to detect if we're running off
the command shell is 'REQUEST_METHOD'.  (Perl's CGI.pm uses REQUEST_METHOD
to figure out if a cgi program is being run from the command line or not.)



So something like:

######
def is_running_as_cgi():
    """Returns True if we're running as a CGI."""
    acceptable = ('POST', 'GET', 'HEAD')
    return os.environ.get('REQUEST_METHOD', '').upper() in acceptable
####

might do the trick.


Best of wishes!



More information about the Tutor mailing list