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

In this previous article I detailed how to set cookies in a CGI script:

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

In this article I am going to describe how to get those cookies in a CGI script.

  1. Get ‘HTTP_COOKIE’ from the Environment variables. Account for the fact that this can be either all upper case, or lower case. cookie_string=os.environ.get('HTTP_COOKIE')
  2. Browsers generally separate cookies based on domain such that cookies for intranet location 1uslchriston.ad.here.com and cookies for the parent domain here.com are kept separately. However, the ‘HTTP_COOKIE’ container that comes from the server groups all cookies of the same parent domain together. For example, it sees ‘here.com’ in the intranet domain 1uslchriston.ad.here.com. Due to this fact, we can’t assume that the one cookie placed from our intranet site is going to be the only cookie in the ‘HTTP_COOKIE’ container. Because of this, we need to first attempt to split our cookie_string by ‘; ‘ like so:
    cookies = cookie_string.split('; ')
  3. Continue to parse the cookies for the pattern set in the previous example. i.e. split on pipe symbol, then ‘=’ sign.
  4. Since there may be more key-value pairs than we want (in this example case there were), create a list of only the keys we are interested in: xml_tool_cookie_keys = ['xml_edit_tool', 'xml_file', 'place']
  5. Then use dictionary comprehension to create a new smaller dictionary that contains only the target keys:
    xmlt_dict = { key: cookie_dict[key] for key in cookie_dict.keys() if key in xml_tool_cookie_keys }

Here is the complete code:

def get_cookies():
    """Return cookie values as a dictionary."""
    cookie_dict = {}
    if 'HTTP_COOKIE' in os.environ or 'http_cookie' in os.environ:
        try:
            cookie_string=os.environ.get('HTTP_COOKIE')
        except:
            cookie_string=os.environ.get('http_cookie')

        # there could be more than one cookie, or cookies from parent domain
        # for example, cookies from 1uslchriston.ad.here.com and here.com
        cookies = cookie_string.split('; ')
        for c in cookies:
            cookie_kv = c.split('|')
            for e in cookie_kv:
                e = e.replace('"', '')
                f = e.split('=')
                k = f[0]
                v = f[1]
                cookie_dict[k] = v

    xml_tool_cookie_keys = ['xml_edit_tool', 'xml_file', 'place']
    xmlt_dict = { key: cookie_dict[key] for key in cookie_dict.keys() if key in xml_tool_cookie_keys }
    return xmlt_dict

Leave a Reply