Skip to main content
 首页 » 编程设计

python之如何在 Django 中为多值 cookie 指定分隔符

2024年08月29日29bluestorm

在 Django 中创建多值 cookie 时,如何指定每个键/值对之间的分隔符,以便 cookie 接收分隔符的 ASCII 字符表示而不是其八进制表示?这是我目前正在做的事情:

uid = 1 
dev = 'computer' 
cookie_value = 'uid:%s,dev:%s' % (uid, dev) 
response.set_cookie(key="profile", value=cookie_value) 

如果我通过 Python 调试器运行它,cookie_value 包含:

'uid:1,dev:computer' 

但是,如果我在浏览器中检查 cookie,我会看到:

'uid:1\054dev:computer' 

如何让 Django 将 '\054' 替换为逗号?

谢谢。

请您参考如下方法:

你的答案是here

Cookie encoding

To fix bugs with cookies in Internet Explorer, Safari, and possibly other browsers, our encoding of cookie values was changed so that the characters comma and semi-colon are treated as non-safe characters, and are therefore encoded as \054 and \073 respectively. This could produce backwards incompatibilities, especially if you are storing comma or semi-colon in cookies and have javascript code that parses and manipulates cookie values client-side.