Processing Parameters Passed to CGI Scripts


#!/usr/bin/pythonimport cgi, sys sys.stderr = sys.stdout data = cgi.FieldStorage() print "Content-type: text/html\n" print "<title>CGI Form Response</title>\n" if data.has_key('name') and data.has_key('quote'):     print "<B>%s</B>: %s" % (data['name'].value, \           data['quote'].value)

The cgi module included with Python provides basic access to the metadata that gets passed to the CGI script when it is executed. When writing a CGI script that needs to accept parameters, use the cgi.FieldStorage() function to parse the fields sent in the POST or GET request to the web server. FieldStorage returns a dictionary of fields that were included with the request.

Parameters can be accessed from the dictionary returned by FieldStorage by using the standard Python syntax to access the keys and values of the dictionary. In the example, has_key(key) is used to determine whether a key exists, and then the value is directly accessed using the d[key].value syntax.

Note

Parameters can be passed to CGI scripts through either a POST or a GET request. The example illustrates how to use a HTML form to send a POST request and a direct link to send a GET request.


#!/usr/bin/pythonimport cgi, sys #Send errors to browser sys.stderr = sys.stdout #Parse data from form data = cgi.FieldStorage() #Send response to browser print "Content-type: text/html\n" print "<title>CGI Form Response</title>\n" print "<h2>Current Quote</h2><P>" if data.has_key('name') and data.has_key('quote'):     print "<B>%s</B>: %s" % (data['name'].value, \           data['quote'].value)


cgi_form.py

<!DOCTYPE html> <html lang="en"> <head> <meta content="text/html; charset=utf-8"  http-equiv="content-type" /> <title>Form Page</title> </head> <body> <h2>Form Post</h2><p> <form method="POST" action="/cgi_form.cgi">     Name <input type="TEXT" name="name">     <P>     Quote <input type="TEXT" name="quote" size="80">     <P>     <input type="SUBMIT" value="send"> </form><p> <h2>Direct Links</h2><p> <li><a href="cgi_form.cgi? name=Brad&quote=G'Day!">G'Day!</a> <li><a href="cgi_form.cgi? name=Brad&quote=Bad Show!">Bad Show!</a> </body> </html>


form.html

Figure 10.2 shows form.html loaded in a web browser.

Figure 10.2. Web browser view of form.html code.


Figure 10.3 shows the web page created when form.html executes cgi_form.cgi.

Figure 10.3. Output HTML page created by cgi_form.cgi code.




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net