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

Once you’ve retrieved a cookie via a function that returns the cookie as a dictionary of key value pairs, you can update the cookie in nearly the same way that you originally set the cookie. The only difference is that this time you can set different values.

In this example, I am passing the retrieved cookie to a function called update_cookie(), along with an updated “current_page” value:

def update_cookie(cookie_dict, current_page):
    """Updates the place value of existing cookie passed in."""
    c = Cookie.SimpleCookie()
    user_value = cookie_dict['xml_edit_tool']
    xml_file_value = cookie_dict['xml_file']
    cookie_string = user_value+'|xml_file='+xml_file_value+'|place='+str(current_page)
    c['xml_edit_tool'] = cookie_string
    print c

Leave a Reply