Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CookieError: Illegal key value

I use web.py, which internally uses the cookie.SimpleCookie class to load cookies incoming from the user's browser.

Occasionally, I get exceptions like:

...
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/Cookie.py", line 455, in set
    raise CookieError("Illegal key value: %s" % key)
CookieError: Illegal key value: SinaRot/g/news.sina.com.cn

The offending character seems to be the forward slash (/), which, according to my reading of RFC 2109 (cookies) and RFC 2068 (HTTP 1.1) should be disallowed, so that's OK.

I don't set this cookie, and I'm not sure why or how it got set for my domain (a proxy, perhaps?), but that's irrelevant; the larger issue is that simplecookie fails hard when it encounters this cookie, and returns an error to the user.

So, my question is: is there any way to ask SimpleCookie to simply ignore cookies that are invalid, but return the rest? I couldn't find anything obvious in the docs to do this.

like image 662
dcrosta Avatar asked Aug 22 '11 13:08

dcrosta


2 Answers

This works for me.

def get_cookies():
    import Cookie
    ans = Cookie.SimpleCookie()
    for bit in os.environ.get('HTTP_COOKIE', '').split('; '):
        try:
            ans.load(bit)
        except Cookie.CookieError:
            pass
    return ans
like image 192
Mark Montague Avatar answered Sep 27 '22 18:09

Mark Montague


When setting cookie name, you should not add space. If there is space in the cookie name, or any space in quotes of the cookie name, it will send you CookieError: Illegal key value

like image 41
Ayush Jha Avatar answered Sep 27 '22 17:09

Ayush Jha