How to setup cookies in Python CGI Programming?

Cookies in Python CGI programming allow you to store small pieces of data on the client's browser. Setting cookies is straightforward − they are sent as HTTP headers before the Content-type field.

Setting Basic Cookies

Cookies are set using the Set-Cookie HTTP header. Here's how to set UserID and Password cookies ?

#!/usr/bin/python3
print("Set-Cookie:UserID=XYZ;\r\n")
print("Set-Cookie:Password=XYZ123;\r\n")
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>Cookies have been set!</h1>")
print("</body></html>")

Setting Cookies with Attributes

You can specify additional attributes like expiration date, domain, and path for better cookie control ?

#!/usr/bin/python3
print("Set-Cookie:UserID=XYZ;\r\n")
print("Set-Cookie:Password=XYZ123;\r\n") 
print("Set-Cookie:Expires=Tuesday, 31-Dec-2025 23:12:40 GMT;\r\n")
print("Set-Cookie:Domain=www.tutorialspoint.com;\r\n")
print("Set-Cookie:Path=/;\r\n")
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>Cookies with attributes have been set!</h1>")
print("</body></html>")

Cookie Attributes

Attribute Purpose Example
Expires Sets cookie expiration date Tuesday, 31-Dec-2025 23:12:40 GMT
Domain Specifies which domain can access the cookie www.tutorialspoint.com
Path Defines the URL path where cookie is valid /

Key Points

  • Cookies must be set before the Content-type header
  • The Set-Cookie header format is: Set-Cookie:name=value;attribute=value;
  • Cookie attributes like Expires, Domain, and Path are optional
  • Each cookie requires a separate Set-Cookie header

Conclusion

Setting cookies in Python CGI is done using Set-Cookie headers before the Content-type header. Optional attributes like expiration, domain, and path provide additional control over cookie behavior.

Updated on: 2026-03-24T20:00:37+05:30

903 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements