CGI Programming
CGI (Common Gateway Interface) is a standard that allows external programs to communicate with a web server. Although less popular nowadays (replaced by WSGI/ASGI), understanding CGI is important for the basics of Python web development.
How CGI works is fairly simple: the web server invokes a Python script every time there is a request from a browser. The output of the script — HTTP headers and HTML content — is sent directly back to the client. Each request triggers a new process, which makes CGI slow at scale. However, this simplicity makes it easier for beginners to understand the request-response flow on the web.
CGI also laid the foundation for many modern web technologies. Popular frameworks such as Flask and Django use WSGI, which is an evolution of the CGI concept. By understanding CGI, you will more easily understand middleware, routing, and response delivery in those frameworks. For simple deployments on local servers or embedded systems, CGI is still relevant to use.
Code Example
#!/usr/bin/env python3
# save as hello.py in the cgi-bin folder
print("Content-Type: text/html")
print() # required blank line
print("""<html>
<body>
<h1>Hello from CGI Python!</h1>
<p>Current time: """)
import datetime
print(datetime.datetime.now())
print("""</p>
</body>
</html>""")
Code Explanation
- The
#!/usr/bin/env python3line is a shebang that tells the server this file must be run with Python 3. print("Content-Type: text/html")sends the HTTP header that tells the browser the content is HTML.print()after the header is the required blank line that separates the HTTP header from the response body.- The script then prints a complete HTML structure with
<html>,<body>tags and an<h1>element. import datetimeandprint(datetime.datetime.now())display the server time when the page is accessed, proving that the content is dynamic.
Everyday Example
A budget hosting provider offers a CGI-based control panel to its customers. When a customer wants to see server status or disk usage, the browser sends a request to the CGI script. The script reads the server configuration, formats it into an HTML page, and sends it back. Simple example: the "Contact Us" page on a static website can use a CGI script to receive form data and send it to the admin's email without needing a big framework.
Summary
CGI is an old technology but essential to learn. It teaches the fundamental concepts of server-client communication, HTTP headers, and dynamic content generation. Although not the main choice for modern applications, understanding CGI is valuable preparation before moving to WSGI/ASGI.