简体   繁体   中英

Decode Django session cookie value

I am setting a session cookie through JavaScript like this:

$('.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"'

using 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 ? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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