0

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

Pavel Vlasov
  • 4,206
  • 6
  • 41
  • 54

1 Answers1

2

Finally the job is done:

  1. cookies escaped with Cookie.SimpleCookie
  2. unescaped with custom code
  3. 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
Pavel Vlasov
  • 4,206
  • 6
  • 41
  • 54