Only the 开发者_开发技巧first word is saved into a cookie using an "example" code if there is a space in value.
What is a really correct, unicode-compatible way to make that?
response.headers.add_header(
'Set-Cookie',
'%s=%s; expires:Sun, 31-May-2020 23:59:59 GMT; path=/;' % (key, value))
UPD. A solution is below
Finally the job is done:
- cookies escaped with Cookie.SimpleCookie
- unescaped with custom code
- unicode encoded/decoded with string's encode/decode
The code:
import Cookie
def set_unicode_cookie(response, key, value):
c = Cookie.SimpleCookie()
c[key] = value.encode('unicode-escape')
c[key]["expires"] = "Sun, 31-May-2020 23:59:59 GMT"
c[key]["path"] = "/"
response.headers.add_header('Set-Cookie', c[key].OutputString())
def get_unicode_cookie(request, key, defult_value):
def unescape(s):
m = re.match(r'^"(.*)"$', s)
s = m.group(1) if m else s
return s.replace("\\\\", "\\")
if request.cookies.has_key(key):
return unescape(request.cookies[key]).decode('unicode-escape')
else:
return default_value
精彩评论