Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What Content-type is required to write Python CGI program?
When writing Python CGI programs, you must specify a Content-type header to tell the browser how to interpret the response. This is essential for proper web communication between your CGI script and the client's browser.
Basic Content-type Header
The first line of any CGI program output must be a Content-type header followed by a blank line ?
#!/usr/bin/env python3
print("Content-type: text/html\r\n\r\n")
print("<html>")
print("<head><title>Hello CGI</title></head>")
print("<body>")
print("<h1>Hello from Python CGI!</h1>")
print("</body>")
print("</html>")
Why the Content-type Header is Required
The Content-type header tells the browser:
- What type of content to expect (HTML, plain text, JSON, etc.)
- How to render or process the response
- What character encoding to use
Common Content-type Values
HTML Content
print("Content-type: text/html\r\n\r\n")
print("<h1>This is HTML content</h1>")
Plain Text Content
print("Content-type: text/plain\r\n\r\n")
print("This is plain text content")
JSON Content
import json
print("Content-type: application/json\r\n\r\n")
data = {"message": "Hello", "status": "success"}
print(json.dumps(data))
Complete CGI Example
Here's a complete Python CGI script that displays system information ?
#!/usr/bin/env python3
import os
import datetime
# Required Content-type header
print("Content-type: text/html\r\n\r\n")
print("<html>")
print("<head><title>System Info</title></head>")
print("<body>")
print("<h2>CGI Environment</h2>")
print("<p>Current time:", datetime.datetime.now(), "</p>")
print("<p>Server software:", os.environ.get('SERVER_SOFTWARE', 'Unknown'), "</p>")
print("<p>Request method:", os.environ.get('REQUEST_METHOD', 'Unknown'), "</p>")
print("</body>")
print("</html>")
Key Points
| Requirement | Format | Purpose |
|---|---|---|
| Content-type header | Content-type: text/html | Specifies content format |
| Line ending | \r\n\r\n | Separates header from body |
| First line | Must be the header | HTTP protocol requirement |
Conclusion
The Content-type header is mandatory for Python CGI programs. Use "text/html" for web pages, "text/plain" for text, and "application/json" for JSON responses. Always include the \r\n\r\n line ending after the header.
Advertisements
