开发者

An universal way to set unicode cookies in Python

开发者 https://www.devze.com 2023-03-23 15:40 出处:网络
Only the 开发者_开发技巧first word is saved into a cookie using an \"example\" code if there is a space in value.

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:

  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
0

精彩评论

暂无评论...
验证码 换一张
取 消