Python on the web: How to delete cookies in a CGI script

After you have a cookie that has been set, here is how you can delete it.

The trick is to send an update to the cookie where you feed it an expiration date that is already in the past. For example:
print "Set-Cookie: xml_edit_tool=Value of cookie; 'expires=Wed, 28 Aug 2013 18:30:00 GMT' \r\n"

Note: When you set this cookie update, you have to use the name of the cookie, in this case it would be ‘xml_edit_tool’.

Here is complete code for a function that can delete cookies based on the cookie name:

#!C:\Python27\python.exe -u

def delete_cookie(cookie_name):
    """Pass the name of the cookie you want deleted and this function will delete it."""
    # Date from the past
    expired_date = 'expires=Wed, 28 Aug 2013 18:30:00 GMT'
    print "Set-Cookie: %s=This could be anything. The important part is the key name xml_edit_tool; %s \r\n" % (cookie_name, expired_date)

delete_cookie('xml_edit_tool')

 

Leave a Reply