dcrosta
dcrosta

Reputation: 26278

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.

Upvotes: 8

Views: 3790

Answers (3)

Ayush Jha
Ayush Jha

Reputation: 21

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

Upvotes: 2

Mark Montague
Mark Montague

Reputation: 31

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

Upvotes: 3

Andrey Kuzmin
Andrey Kuzmin

Reputation: 4479

My webpy app has experienced CookieError: Illegal key value: )|utmcmd set by Google Analytics in Firefox browser. To fix it I issue redirect trying to set correct value.

def myinternalerror(): 
    try: 
        web.cookies() 
    except CookieError: 
        if not "cookie_err" in web.input(): 
            web.setcookie("__utmz", None, domain=web.ctx.host) 
            raise web.seeother(web.changequery(cookie_err=1)) 
    return web.internalerror(render.site.e500()) 

if not web.config.debug:
    app.internalerror = myinternalerror

Upvotes: 0

Related Questions