- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the modules required for CGI programming in Python?
Python's cgi module is usually the starting place in writing CGI programs in Python. The main purpose of the cgi module is to extract the values passed to a CGI program from an HTML form. Mostly one interacts with CGI applications through an HTML form. One fills out some values in the form that specify details of the action to be performed, then call on the CGI to perform its action using your specifications.
You may include many input fields within an HTML form which can be of a number of different types (text, checkboxes, picklists, radio buttons, etc.).
Your Python script should begin with import cgi. The main thing done by the CGI module is to treat all the fields in the calling HTML form in a dictionary-like fashion. What you get is not exactly a Python dictionary, but it is easy to work with. Let's see an example −
Example
import cgi form = cgi.FieldStorage() # FieldStorage object to # hold the form data # check whether a field called "username" was used... # it might be used multiple times (so sep w/ commas) if form.has_key('username'): username = form["username"] usernames = "" if type(username) is type([]): # Multiple username fields specified for item in username: if usernames: # Next item -- insert comma usernames = usernames + "," + item.value else: # First item -- don't insert comma usernames = item.value else: # Single username field specified usernames = username.value # just for the fun of it let's create an HTML list # of all the fields on the calling form field_list = '<ul>\n' for field in form.keys(): field_list = field_list + '<li>%s</li>\n' % field field_list = field_list + '</ul>\n'
We'll have to do more to present a useful page to the user, but we've made a good beginning by working on a submitting form.