简体   繁体   English

解码 Django 会话 cookie 值

[英]Decode Django session cookie value

I am setting a session cookie through JavaScript like this:我正在通过JavaScript设置会话 cookie,如下所示:

$('.content li a').on('click', function(e) {
        $.cookie.json = true;
        var cookie_value = {postid: 1234, commentid: 8999};
        $.cookie('my_cookie_key', cookie_value, {path: '/'});
    });

When I try to retrieve the cookie value in Python Django, I get an encode string like this: '"%7B%22postid%22%3A1234%2C%22commentid%22%3A8999%7D"'当我尝试在 Python Django 中检索 cookie 值时,我得到一个这样的编码字符串: '"%7B%22postid%22%3A1234%2C%22commentid%22%3A8999%7D"'

using request.COOKIES.get('my_cookie_key')使用request.COOKIES.get('my_cookie_key')

How can I turn it into a dict object so I can easily retrieve all the values in the cookie like my_cookie_obj.postid ?我怎样才能把它变成一个dict对象,这样我就可以轻松地检索 cookie 中的所有值,比如my_cookie_obj.postid I have tried decoding the string but I don't think I am doing it right.我试过解码字符串,但我认为我做得不对。

The value is simply percent encoded.该值是简单的百分比编码。 Just use the appropriate decoding functions and you should get back what you store.只需使用适当的解码功能,您就应该取回您存储的内容。

>>> import json
>>> from urllib.parse import unquote
>>> s = unquote("%7B%22postid%22%3A1234%2C%22commentid%22%3A8999%7D")
>>> s
'{"postid":1234,"commentid":8999}'
>>> v = json.loads(s)
>>> v['commentid']
8999

Do note that users can manipulate all cookie values, so do take care when parsing/using the values as they are untrusted content.请注意,用户可以操纵所有 cookie 值,因此在解析/使用这些值时要小心,因为它们是不受信任的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM