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
CGI Environment Variables in Python
All CGI programs have access to environment variables that contain important information about the request, server, and client. These variables play an important role while writing any CGI program.
Common CGI Environment Variables
| Variable Name | Description |
|---|---|
| CONTENT_TYPE | The data type of the content. Used when the client is sending attached content to the server (e.g., file upload). |
| CONTENT_LENGTH | The length of the query information. Available only for POST requests. |
| HTTP_COOKIE | Returns the set cookies in the form of key-value pairs. |
| HTTP_USER_AGENT | Contains information about the user agent (web browser) originating the request. |
| PATH_INFO | The path for the CGI script. |
| QUERY_STRING | The URL-encoded information that is sent with GET method request. |
| REMOTE_ADDR | The IP address of the remote host making the request. Useful for logging or authentication. |
| REMOTE_HOST | The fully qualified name of the host making the request. If not available, use REMOTE_ADDR. |
| REQUEST_METHOD | The method used to make the request. Most common methods are GET and POST. |
| SCRIPT_FILENAME | The full path to the CGI script. |
| SCRIPT_NAME | The name of the CGI script. |
| SERVER_NAME | The server's hostname or IP address. |
| SERVER_SOFTWARE | The name and version of the software the server is running. |
Accessing Environment Variables
Here is a simple CGI program to list all available CGI environment variables ?
#!/usr/bin/python3
import os
print("Content-type: text/html\r\n\r\n")
print("<html><body>")
print("<h1>CGI Environment Variables</h1>")
for param in os.environ.keys():
print("<b>{}</b>: {}<br>".format(param, os.environ[param]))
print("</body></html>")
Accessing Specific Variables
You can access specific environment variables using the os.environ dictionary ?
import os
# Simulate some CGI environment variables for demonstration
os.environ['REQUEST_METHOD'] = 'GET'
os.environ['QUERY_STRING'] = 'name=john&age=25'
os.environ['HTTP_USER_AGENT'] = 'Mozilla/5.0'
# Access specific variables
request_method = os.environ.get('REQUEST_METHOD', 'Unknown')
query_string = os.environ.get('QUERY_STRING', '')
user_agent = os.environ.get('HTTP_USER_AGENT', 'Unknown')
print(f"Request Method: {request_method}")
print(f"Query String: {query_string}")
print(f"User Agent: {user_agent}")
Request Method: GET Query String: name=john&age=25 User Agent: Mozilla/5.0
Conclusion
CGI environment variables provide essential information about HTTP requests and server configuration. Use os.environ to access these variables in your CGI scripts for processing user requests and generating appropriate responses.
Advertisements
