Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to process a simple form data using Python CGI script?
Python CGI (Common Gateway Interface) allows web servers to execute Python scripts and process form data. When a user submits an HTML form, the CGI script can retrieve and process the submitted data.
HTML Form Setup
First, create an HTML form that sends data to a Python CGI script ?
<form action="getData.py" method="post"> FirstName: <input type="text" name="first_name"> LastName: <input type="text" name="last_name"> <input type="submit" value="Submit"> </form>
This form collects first and last names, then sends the data to getData.py using the POST method.
Python CGI Script
Create the getData.py script to process the form data ?
#!/usr/bin/env python3
# Import modules for CGI handling
import cgi
import cgitb
# Enable CGI error reporting
cgitb.enable()
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from form fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
# Print HTTP header
print("Content-Type: text/html\n")
# Generate HTML response
print("<html>")
print("<head><title>Form Processing Result</title></head>")
print("<body>")
print("<h2>Hello - Form Data Processing</h2>")
if first_name and last_name:
print("<h3>Hello %s %s</h3>" % (first_name, last_name))
else:
print("<p>Please provide both first and last names.</p>")
print("</body>")
print("</html>")
How It Works
The CGI script follows these key steps:
-
Import modules:
cgifor form handling andcgitbfor error reporting -
Create FieldStorage:
cgi.FieldStorage()parses form data from the request -
Extract values:
getvalue()retrieves specific field values by name - Generate response: Print HTTP headers followed by HTML content
Key Points
- Always print the
Content-Typeheader before any HTML output - Include a blank line after headers using
\n - Use
cgitb.enable()for debugging CGI errors - Validate form data before processing to handle empty fields
- The shebang line
#!/usr/bin/env python3tells the server which interpreter to use
Server Configuration
To run CGI scripts, your web server must be configured to execute Python files. Place the script in the server's cgi-bin directory and ensure it has execute permissions.
Conclusion
Python CGI scripts use the cgi module to process HTML form data. The FieldStorage class parses form data, while getvalue() retrieves specific field values for processing and response generation.
