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 do cookies work in Python CGI Programming?
HTTP protocol is a stateless protocol, meaning it doesn't remember information between requests. For commercial websites, it's essential to maintain session information across different pages. For example, user registration may span multiple pages, requiring session data persistence.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
How Cookies Work
Your server sends data to the visitor's browser in the form of a cookie. The browser may accept the cookie and store it as a plain text record on the visitor's hard drive. When the visitor arrives at another page on your site, the cookie becomes available for retrieval, allowing your server to remember stored information.
Cookie Structure
Cookies are plain text data records containing 5 variable-length fields ?
- Name=Value − Cookies are set and retrieved as key-value pairs
- Domain − The domain name of your site
- Path − The path to the directory or web page that sets the cookie. May be blank to retrieve from any directory
- Expires − The expiration date. If blank, cookie expires when browser closes
- Secure − If contains "secure", cookie only retrieved over HTTPS connections
Setting Cookies in Python CGI
In Python CGI, you set cookies using the Set-Cookie HTTP header ?
#!/usr/bin/env python3
import cgi
# Set cookie header before any output
print("Set-Cookie: username=john_doe; Path=/; Max-Age=3600")
print("Content-Type: text/html\n")
print("<html><body>")
print("<h2>Cookie has been set!</h2>")
print("<p>Username cookie set to: john_doe</p>")
print("</body></html>")
Reading Cookies in Python CGI
Retrieve cookies from the HTTP_COOKIE environment variable ?
#!/usr/bin/env python3
import os
print("Content-Type: text/html\n")
# Get cookies from environment
cookie_string = os.environ.get('HTTP_COOKIE', '')
print("<html><body>")
print("<h2>Reading Cookies</h2>")
if cookie_string:
# Parse cookies
cookies = {}
for cookie in cookie_string.split(';'):
if '=' in cookie:
name, value = cookie.strip().split('=', 1)
cookies[name] = value
print("<p>Found cookies:</p><ul>")
for name, value in cookies.items():
print(f"<li>{name} = {value}</li>")
print("</ul>")
else:
print("<p>No cookies found</p>")
print("</body></html>")
Complete Cookie Example
Here's a complete CGI script that sets and reads cookies ?
#!/usr/bin/env python3
import cgi
import os
from datetime import datetime, timedelta
# Create form object
form = cgi.FieldStorage()
# Check if setting new cookie
if "set_cookie" in form:
username = form.getvalue("username", "anonymous")
# Set cookie with 1 hour expiration
expires = datetime.now() + timedelta(hours=1)
expires_str = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
print(f"Set-Cookie: username={username}; Path=/; Expires={expires_str}")
print("Content-Type: text/html\n")
# Read existing cookies
cookies = {}
cookie_string = os.environ.get('HTTP_COOKIE', '')
if cookie_string:
for cookie in cookie_string.split(';'):
if '=' in cookie:
name, value = cookie.strip().split('=', 1)
cookies[name] = value
print("<html><body>")
print("<h2>Cookie Manager</h2>")
# Display current cookies
if cookies:
print("<h3>Current Cookies:</h3><ul>")
for name, value in cookies.items():
print(f"<li>{name}: {value}</li>")
print("</ul>")
else:
print("<p>No cookies set</p>")
# Form to set new cookie
print("""
<h3>Set New Cookie:</h3>
<form method="post">
<label>Username: <input type="text" name="username" value="john_doe"></label>
<input type="hidden" name="set_cookie" value="1">
<input type="submit" value="Set Cookie">
</form>
""")
print("</body></html>")
Conclusion
Cookies in Python CGI are managed through HTTP headers ? use Set-Cookie to send cookies and read HTTP_COOKIE environment variable to retrieve them. Always set cookies before any HTML output to avoid header errors.
