[Tutor] Input from CGI ?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Nov 3 22:34:46 CET 2004



On Wed, 3 Nov 2004, Mark Kels wrote:

> How can I get input (string) from the user in CGI ?


Hi Mark,


There are examples of doing this in the Standard Library documentation.
Here's a link to the documentation on the 'cgi' module:

    http://www.python.org/doc/lib/module-cgi.html

The idea is to use the cgi module to grab form values.  There are several
methods we can use, but the easiest one is probably
FieldStorage.getfirst().


Here's a quick example CGI program that takes in a number and prints out
its square:


###
#!/usr/bin/python

"""A small program to demonstrate simple CGIish stuff."""

import cgi
import cgitb; cgitb.enable()


def main():
    form = cgi.FieldStorage()
    if form.getfirst("number"):
        doComputationAndPrintResult(form)
    else:
        printStartPage()


def printStartPage():
    printHtmlHeader()
    print """
    <html><body>
    <form><input name="number" type="text"></form>
    </body></html>
    """


def doComputationAndPrintResult(form):
    computedResult = square(int(form.getfirst("number")))

    printHtmlHeader()
    print """
    <html><body>
    %s
    </body></html>
    """ % computedResult


def printHtmlHeader():
    """Prints out the standard HTML header line."""
    print "Content-type: text/html\n\n"


def square(x):
    """Returns the square of x."""
    return x * x


if __name__ == '__main__':
    main()
###


You might also like to browse through the Web Programming topic guide
here:

    http://www.python.org/topics/web/


Good luck to you!



More information about the Tutor mailing list