Python CGI Basics – Common Gateway Interface in Python

Introduction

Before modern web frameworks like Flask and Django became popular, one of the earliest ways to create dynamic web pages using Python was through CGI (Common Gateway Interface). CGI allows a web server to execute external programs and generate dynamic content that is sent back to the user’s browser.

Python CGI is now largely replaced by more efficient technologies.

What is CGI?

CGI (Common Gateway Interface) is a standard protocol that enables web servers to execute external programs and generate dynamic web content.

When a user requests a web page, the web server can run a CGI script, process the request, and return the generated output to the browser.

CGI acts as a bridge between:

  • Web Browser
  • Web Server
  • Backend Program (Python Script)

Why Use CGI?

CGI was developed to overcome the limitations of static HTML pages.

With CGI, developers can:

  • Generate dynamic web pages
  • Process form data
  • Interact with databases
  • Perform calculations
  • Create web applications
  • Handle user authentication

How CGI Works?

The CGI process follows these steps:


User Browser
      ↓
HTTP Request
      ↓
Web Server
      ↓
CGI Script Execution
      ↓
Process Request
      ↓
Generate Response
      ↓
Web Server
      ↓
Browser Displays Result

CGI Architecture

A CGI-based web application consists of three main components:

1. Client

The user’s web browser sends requests.

Example:

  • Chrome
  • Firefox
  • Edge

2. Web Server

The server receives requests and executes CGI scripts.

Examples:

  • Apache
  • Nginx
  • IIS

3. CGI Program

The Python script processes data and generates output.

Advantages of CGI

There are many advantages of CGI

  1. Platform Independent
  2. Language Independent
  3. Dynamic Content Generation
  4. Easy Integration

Limitations of CGI

There are many limitations of CGI

  1. Slow Performance
  2. High Resource Usage
  3. Not Suitable for Modern Large Applications
  4. Difficult Maintenance

Setting Up Python CGI

To run CGI scripts:

Step 1: Install Python

Verify installation:


python --version

Output:

Python 3.x.x

Step 2: Configure Web Server

Enable CGI support in:

  • Apache Server
  • IIS
  • Other CGI-compatible servers

Step 3: Create CGI Directory

Typically:


cgi-bin/

Place CGI scripts inside this directory.

Create Python CGI Program

Create a file named:


hello.py

Example:


#!/usr/bin/python3
print("Content-Type: text/html")
print()
print("<h1>Hello World!</h1>")

Understanding the Code of the Above Program

Shebang Line


#!/usr/bin/python3

Tells the server which interpreter should execute the script.

Content-Type Header


print("Content-Type: text/html")

Informs the browser that HTML content is being returned.

Blank Line


print()

Separates HTTP headers from content.

HTML Output

print(“<h1>Hello World!</h1>”)

Displays HTML content in the browser.

The browser displays:

Hello World!

How to use CGI Module?

Python provides a built-in CGI module for handling form data.

Import CGI Module


import cgi

Handling User Input

Suppose we have an HTML form:


<form action="welcome.py" method="post">
    Name:
    <input type="text" name="username">
    <input type="submit">
</form>

Reading Form Data

Example:


#!/usr/bin/python3
import cgi
form = cgi.FieldStorage()
name = form.getvalue(
    "username"
)
print("Content-Type:text/html")
print()
print(
     "<h1>Hello",
    name,
    "</h1>"
)

Output:

If the user enters: John

Output:

<h1>Hello John</h1>

GET Method in CGI

The GET method sends data through the URL.

Example URL:


https://example.com/script.py?name=John

Advantages:

  • Simple
  • Easy to test

Disadvantages:

  • Data visible in URL
  • Limited size

POST Method in CGI

The POST method sends data in the request body.

Example:


<form method="post">

Advantages:

  • More secure
  • Supports large data

Disadvantages:

  • Slightly more processing

Example: Addition Calculator Using CGI

HTML Form


<form action="add.py" method="post">
Number 1:
<input type="text" name="num1">
Number 2:
<input type="text" name="num2">
<input type="submit" value="Add">
</form>

CGI Script


#!/usr/bin/python3
import cgi
form = cgi.FieldStorage()
num1 = int(
    form.getvalue("num1")
)
num2 = int(
    form.getvalue("num2")
)
result = num1 + num2
print("Content-Type:text/html")
print()
print(
    "<h2>Result:",
    result,
    "</h2>"
)

Working with Environment Variables

CGI provides useful environment variables.

Example:


import os
print(
    os.environ[
        "REQUEST_METHOD"
    ]
)

Common Variables:

Variable Description
REQUEST_METHOD GET or POST
QUERY_STRING URL Parameters
REMOTE_ADDR Client IP Address
HTTP_USER_AGENT Browser Information
SERVER_NAME Server Name

Real-Life Example

Suppose a website has a registration form.

The user enters:

  • Name
  • Email
  • Password

A CGI script can:

  1. Receive form data.
  2. Validate user input.
  3. Store information in a database.
  4. Display a success message.

This was a common approach before modern frameworks became widespread.

Common Mistakes

1. Missing Content-Type Header

Incorrect:


print("<h1>Hello</h1>")

Correct:


print("Content-Type:text/html")
print()

Without headers, the browser may display errors.

2. Missing Blank Line

Incorrect:


print("Content-Type:text/html")
print("<h1>Hello</h1>")

Correct:


print("Content-Type:text/html")
print()
print("<h1>Hello</h1>")

3. Incorrect File Permissions

CGI scripts must be executable.

Linux:


chmod 755 hello.py

4. Not Validating User Input

Incorrect:


num = int(
    form.getvalue("num")
)

Invalid input can cause exceptions.

Use validation and exception handling.

Conclusion

Python CGI is one of the earliest technologies used for creating dynamic web applications. It allows web servers to execute Python scripts, process user requests, and generate dynamic content.

CGI has largely been replaced by modern frameworks such as Flask, Django, and FastAPI.

Related Python Tutorials