Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Click here to view code image


<input type="text" name="lname" />

The Apache server passes the data into the shell environment for the script so that the Python script
can retrieve it.


The Python cgi module provides the necessary elements for your Python script to retrieve the shell
environment data so you can process it in your Python script. The FieldStorage class in the cgi
module provides the methods for you to access the data. To retrieve the form data, you need to create
an instance of the FieldStorage class in your Python code, as shown here:


Click here to view code image


import cgi
formdata = cgi.FieldStorage()

After you create the FieldStorage instance, you need to use two methods to retrieve the form
data:


getfirst()
getlist()

The getfirst() method retrieves only the first occurrence of a key name as a string value. You
use this to retrieve text box, radio button, and text area form values.


Watch Out!: Numeric Form Fields
The getfirst() method returns the form data as string values, even if the string
value is a number. You need to use the Python type conversion methods to convert the
data into numeric values, if necessary.

The getlist() method retrieves multiple values as a list value. You use it to retrieve the check
box values. The web form returns the values of any selected check boxes in the list object.


Now you’re ready to write the script2208.cgi file to process the form data. Listing 22.5 shows
the code you use.


LISTING 22.5 Processing Form Data in a Python Script


Click here to view code image


1: #!/usr/bin/python3
2:
3: import cgi
4: formdata = cgi.FieldStorage()
5: lname = formdata.getfirst('lname', '')
6: fname = formdata.getfirst('fname', '')
7: age = formdata.getfirst('age', '')
8: comment = formdata.getfirst('comment', '')
9:
10: print('Content-Type: text/html')
11: print('')
12: print('''<!DOCTYPE html>
13: <html>
14: <head>
Free download pdf