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
Selected Reading
How to pass Text Area Data to Python CGI script?
The TEXTAREA element allows users to input multiline text data that can be processed by a Python CGI script. This is useful for forms that need to collect longer text content like comments, descriptions, or messages.
HTML Form with TEXTAREA
Here is the HTML code for creating a form with a TEXTAREA element ?
<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank"> <textarea name = "textcontent" cols = "40" rows = "4"> Type your text here... </textarea> <input type = "submit" value = "Submit" /> </form>
The result of this code is the following form ?
Type your text here... Submit
Python CGI Script
Below is the textarea.py script to handle the textarea input from the web browser ?
#!/usr/bin/python3
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
else:
text_content = "Not entered"
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Text Area - CGI Program</title>")
print("</head>")
print("<body>")
print("<h2>Entered Text Content is %s</h2>" % text_content)
print("</body>")
print("</html>")
How It Works
The CGI script processes the textarea data in the following steps:
-
cgi.FieldStorage()creates an instance to access form data -
form.getvalue('textcontent')retrieves the textarea content - The script checks if data exists, otherwise sets a default message
- HTML content-type header is sent followed by the response page
Key Points
- Use
method="post"for textarea forms to handle larger text content - The
nameattribute in textarea must match the parameter ingetvalue() - Always include proper error handling for missing form data
- Remember to set the correct content-type header for HTML output
Conclusion
Passing textarea data to Python CGI scripts involves creating an HTML form with a textarea element and processing the submitted data using the cgi module. The FieldStorage class handles form data extraction efficiently.
Advertisements
