How to send the result of Python CGI script to the browser?

A Python CGI script runs on a web server and sends dynamic HTML content to the browser. To send results from your CGI script to the browser, you need to output proper HTTP headers followed by HTML content.

Basic CGI Response Structure

Every CGI script must start with a content-type header, followed by a blank line, then the HTML content ?

#!/usr/bin/env python3
import cgi

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from HTML form fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')

# Send HTTP header
print("Content-type:text/html")
print()  # Blank line required

# Send HTML content
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print("<h2>Hello %s %s</h2>" % (first_name, last_name))
print("</body>")
print("</html>")

Complete CGI Script Example

Here's a complete working CGI script that processes form data and sends formatted results ?

#!/usr/bin/env python3
import cgi
import cgitb

# Enable CGI error reporting
cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get form data
first_name = form.getvalue('first_name', 'Unknown')
last_name = form.getvalue('last_name', 'User')

# Send content-type header
print("Content-type:text/html\r\n\r\n")

# Generate HTML response
print("""
<!DOCTYPE html>
<html>
<head>
    <title>CGI Response</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 50px; }
        .greeting { color: #333; background: #f0f0f0; padding: 20px; }
    </style>
</head>
<body>
    <div class="greeting">
        <h2>Hello %s %s!</h2>
        <p>Welcome to our CGI application.</p>
    </div>
</body>
</html>
""" % (first_name, last_name))

Key Points

  • The Content-type header tells the browser what type of content to expect
  • A blank line must separate the headers from the HTML content
  • Use form.getvalue() to safely retrieve form data with optional default values
  • Enable cgitb for better error debugging during development
  • HTML-encode user input to prevent XSS attacks in production applications

HTTP Headers for Different Content Types

Content Type Header Use Case
HTML Content-type:text/html Web pages
JSON Content-type:application/json API responses
Plain Text Content-type:text/plain Simple text output
XML Content-type:text/xml XML documents

Conclusion

To send CGI script results to the browser, always start with the proper Content-type header, add a blank line, then output your HTML content. Use cgi.FieldStorage() to safely handle form data and consider enabling cgitb for debugging.

Updated on: 2026-03-24T20:02:35+05:30

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements