Python CGI Programming
Before modern frameworks like Flask and Django became popular, websites used a technology called CGI (Common Gateway Interface) to generate dynamic web content.
Python supports CGI programming, allowing scripts to run on a web server and generate HTML dynamically.
CGI is useful for:
- Handling web forms
- Processing user input
- Generating dynamic HTML pages
- Simple web applications
- Learning basic web server concepts
What is CGI?
CGI (Common Gateway Interface) is a protocol that allows a web server to execute external programs and return their output to a browser.
Flow of CGI:
Browser → Web Server → CGI Script (Python) → Output → BrowserWhy Use CGI?
CGI helps:
- Create dynamic web pages
- Process form data
- Interact with backend scripts
- Learn how web servers work
Although modern frameworks replaced CGI, it is still useful for learning fundamentals.
Enabling CGI in Python
To run CGI scripts, you need:
- A web server (Apache or built-in server)
- CGI enabled directory
- Python installed
Writing Your First CGI Script
Create a file: hello.py
#!/usr/bin/env python3
print("Content-type: text/html\n")
print("<html>")
print("<body>")
print("<h1>Hello from Python CGI</h1>")
print("</body>")
print("</html>")Explanation
#!/usr/bin/env python3→ shebang lineContent-type→ tells browser it's HTML- HTML output is printed using Python
Running CGI Script (Linux/Apache)
- Place file in
cgi-binfolder - Give execute permission:
chmod +x hello.py- Access via browser:
http://localhost/cgi-bin/hello.pyHandling Forms in CGI
HTML Form
<form action="/cgi-bin/form.py" method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>Python CGI Form Handling
#!/usr/bin/env python3
import cgi
print("Content-type: text/html\n")
form = cgi.FieldStorage()
name = form.getvalue("name")
print("<html><body>")
print(f"<h1>Hello {name}</h1>")
print("</body></html>")GET vs POST Method
GET Method
- Data sent via URL
- Visible in browser
Example:
/cgi-bin/form.py?name=JohnPOST Method
- Data sent in request body
- More secure
Reading GET Data
import os
import cgi
print("Content-type: text/html\n")
query = os.environ["QUERY_STRING"]
print(query)CGI Environment Variables
| Variable | Description |
|---|---|
| REQUEST_METHOD | GET or POST |
| QUERY_STRING | URL parameters |
| CONTENT_LENGTH | Data size |
| SCRIPT_NAME | Script path |
| REMOTE_ADDR | Client IP |
Example: Display Environment Info
import os
print("Content-type: text/html\n")
print("<pre>")
for key in os.environ:
print(key, "=", os.environ[key])
print("</pre>")CGI with HTML Output
print("Content-type: text/html\n")
print("""
<html>
<head><title>CGI Page</title></head>
<body>
<h1>Dynamic CGI Page</h1>
</body>
</html>
""")Advantages of CGI Programming
- Simple to understand
- Works with many languages
- Direct server execution
- Good for learning web basics
Disadvantages of CGI
- Slow performance (new process per request)
- Not scalable for large applications
- Outdated compared to modern frameworks
- High resource usage
CGI vs Modern Frameworks
| Feature | CGI | Flask/Django |
| Speed | Slow | Fast |
| Scalability | Low | High |
| Complexity | Simple | Moderate |
| Usage Today | Rare | Common |
Real-World Use Cases
CGI is used in:
- Legacy systems
- Simple web scripts
- Educational purposes
- Server-side automation scripts
Security Considerations
- Validate all user input
- Avoid command injection
- Sanitize form data
- Restrict file permissions
Example: Simple Calculator CGI
#!/usr/bin/env python3
import cgi
print("Content-type: text/html\n")
form = cgi.FieldStorage()
a = int(form.getvalue("a"))
b = int(form.getvalue("b"))
result = a + b
print(f"<h1>Result: {result}</h1>")Best Practices
- Always include Content-type header
- Validate user input
- Use proper permissions
- Keep scripts simple
- Avoid complex logic in CGI scripts
Summary
Python CGI programming allows developers to create dynamic web pages using simple scripts executed by a web server. It helps understand how web servers process requests and generate responses.
Conclusion
Although CGI is an older technology, it remains important for learning how web servers work. Python makes CGI scripting easy with simple syntax and built-in modules.
Understanding CGI helps build a strong foundation before moving to modern frameworks like Flask and Django.


0 Comments