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
How to retrieve cookies in Python CGI Programming?
Retrieving cookies in Python CGI programming allows you to access data stored in the user's browser. Cookies are stored in the CGI environment variable HTTP_COOKIE and can be parsed to extract individual values.
Cookie Storage Format
Cookies are stored in the HTTP_COOKIE environment variable in the following format ?
key1=value1;key2=value2;key3=value3....
Basic Cookie Retrieval
Here's how to retrieve and parse cookies from the environment variable ?
#!/usr/bin/env python3
# Import modules for CGI handling
import os
import cgi
# Check if cookies exist
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
# Parse cookies
for cookie in cookies.split(';'):
cookie = cookie.strip() # Remove whitespace
if '=' in cookie:
key, value = cookie.split('=', 1)
if key == "UserID":
user_id = value
elif key == "Password":
password = value
print("Content-Type: text/html\n")
print(f"User ID = {user_id}")
print(f"Password = {password}")
else:
print("Content-Type: text/html\n")
print("No cookies found")
This produces the following result for cookies set previously ?
User ID = XYZ Password = XYZ123
Using a Dictionary for Cookie Storage
A more organized approach is to store all cookies in a dictionary ?
#!/usr/bin/env python3
import os
def get_cookies():
cookies = {}
if 'HTTP_COOKIE' in os.environ:
cookie_string = os.environ['HTTP_COOKIE']
for cookie in cookie_string.split(';'):
cookie = cookie.strip()
if '=' in cookie:
key, value = cookie.split('=', 1)
cookies[key] = value
return cookies
# Retrieve all cookies
user_cookies = get_cookies()
print("Content-Type: text/html\n")
if user_cookies:
for key, value in user_cookies.items():
print(f"{key} = {value}")
else:
print("No cookies available")
Error Handling
Always include error handling when working with cookies ?
#!/usr/bin/env python3
import os
def safe_get_cookie(cookie_name):
try:
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
for cookie in cookies.split(';'):
cookie = cookie.strip()
if '=' in cookie:
key, value = cookie.split('=', 1)
if key == cookie_name:
return value
return None
except Exception as e:
return None
# Safe cookie retrieval
user_id = safe_get_cookie("UserID")
password = safe_get_cookie("Password")
print("Content-Type: text/html\n")
print(f"User ID: {user_id if user_id else 'Not found'}")
print(f"Password: {password if password else 'Not found'}")
Key Points
- Cookies are stored in the
HTTP_COOKIEenvironment variable - Multiple cookies are separated by semicolons
- Each cookie follows the format
key=value - Always check if
HTTP_COOKIEexists before parsing - Use proper error handling to avoid crashes
Conclusion
Retrieving cookies in Python CGI involves parsing the HTTP_COOKIE environment variable. Use dictionary storage and error handling for robust cookie management in your CGI applications.
