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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With