1.

What is FieldStorage class in Python? Explain its usage.

Answer»

FieldStorage class is defined in cgi module of Python’s standard library. 

A http server can be configured to run executable scripts and programs stored in the cgi-bin directory on the server and render response in HTML form towards client. For EXAMPLE a Python script can be executed from cgi-bin directory.

However, the input to such a script may come from the client in the form of HTTP request either via its GET method or POST method.

In following HTML script, a form with two text input elements are defined. User data is sent as a HTTP request to a script mentioned as parameter of ‘action’ attribute with GET method.

<form action = "/cgi-bin/test.py" method = "get"> Name: <input type = "text" name = "name">  <br /> address: <input type = "text" name = "ADDR" /> <input type = "submit" VALUE = "Submit" /> </form>

In order to process the user input, Python’s CGI script makes use of FieldStorage object. This object is actually a dictionary object with HTML form elements as key and user data as value.

#!/usr/bin/python # Import CGI module  import cgi # Create INSTANCE of FieldStorage  fso = cgi.FieldStorage()

The fso object now contains form data which can be retrieved using usual dictionary notation.

nm = fso[‘name’] add=fso[‘addr’]

FieldStorage class also defines the following methods:

  • getvalue(): This method RETRIEVES value associated with form element. 
  • getfirst(): This method returns only one value associated with form field name. The method returns only the first value in case more values were given under such name.
  • getlist():This method always returns a list of values associated with form field name.


Discussion

No Comment Found