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:

  1. cgi.FieldStorage() creates an instance to access form data
  2. form.getvalue('textcontent') retrieves the textarea content
  3. The script checks if data exists, otherwise sets a default message
  4. 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 name attribute in textarea must match the parameter in getvalue()
  • 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.

Updated on: 2026-03-24T20:03:27+05:30

901 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements