legacy-cgi

2.6.4 · maintenance · verified Thu Apr 09

legacy-cgi is a fork of the standard library `cgi` and `cgitb` modules, which were removed from Python's standard library in version 3.13 as per PEP 594. Its primary purpose is to provide a drop-in replacement to support existing CGI scripts and applications that rely on these modules, ensuring compatibility for Python 3.13+. The current version is 2.6.4, with development focused on maintaining compatibility and applying bug fixes rather than introducing new features.

Warnings

Install

Imports

Quickstart

This example demonstrates a basic CGI script that processes form data using `cgi.FieldStorage`. To run this, save the code as a `.py` file (e.g., `my_cgi_script.py`), make it executable (`chmod +x my_cgi_script.py`), and place it in your web server's configured CGI directory (e.g., `cgi-bin`). The script prints HTTP headers followed by HTML content to the standard output, which the web server then sends to the client.

# Save this as 'my_cgi_script.py' in your web server's cgi-bin directory
# and ensure it's executable (e.g., chmod +x my_cgi_script.py)

import cgi
import cgitb
import os

# Enable traceback manager for CGI scripts (useful for debugging)
# In a production environment, consider logging errors instead of displaying them.
cgitb.enable()

print("Content-Type: text/html")
print() # Empty line signifies end of HTTP headers

print("<!DOCTYPE html>")
print("<html>")
print("<head><title>Legacy CGI Example</title></head>")
print("<body>")
print("<h1>Simple CGI Form</h1>")

form = cgi.FieldStorage()

name = form.getvalue("name", "Guest")
message = form.getvalue("message", "No message provided.")

if form.getvalue("submit"):
    print(f"<p>Hello, <strong>{name}</strong>!</p>")
    print(f"<p>Your message: <em>{message}</em></p>")
else:
    print("<p>Please fill out the form:</p>")

print('<form method="post" action="my_cgi_script.py">')
print('  <label for="name">Name:</label><br>')
print('  <input type="text" id="name" name="name" value=""><br><br>')
print('  <label for="message">Message:</label><br>')
print('  <textarea id="message" name="message" rows="4" cols="50"></textarea><br><br>')
print('  <input type="submit" name="submit" value="Submit">')
print('</form>')

print("</body>")
print("</html>")

view raw JSON →