Next / Previous / Contents / TCC Help System / NM Tech homepage

5.3. main(): The main program

Execution starts here. The first order of business is to write a header line and blank line that informs the Web server that we intend to generate a page of HTML.

anyform.cgi
# - - -   m a i n

def main():
    '''Main program.
    '''
    print 'Content-type: text/html'
    print

We'll use the ElementTree module to build the output Web page. Refer to Section 5.1, “XHTML to be generated” for the structure of the HTML we are building here.

anyform.cgi
    html  =  et.Element ( 'html' )
    page  =  et.ElementTree ( html )
    head  =  et.SubElement ( html, 'head' )
    title  =  et.SubElement ( head, 'title' )
    title.text  =  'Form output test'

    body  =  et.SubElement ( html, 'body' )
    h1  =  et.SubElement ( body, 'h1' )
    h1.text  =  'Form output test'

Next we'll get the FieldStorage instance and use its .keys() method to get a list of all the incoming control names. We'll sort the control names so they always appear in alphabetical order.

anyform.cgi
    form  =  cgi.FieldStorage()
    nameList  =  form.keys()
    nameList.sort()

This loop goes through the control names and, for each one, calls the showControl() function to add a div element to the page body, displaying the value of that control.

anyform.cgi
    for cName in nameList:
        showControl ( body, form, cName )

Finally, we use the ElementTree.write() method to send the HTML for the page to the standard output stream.

anyform.cgi
    page.write ( sys.stdout )