最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to read flask sessions using javascript? - Stack Overflow

programmeradmin3浏览0评论

I have a secured flask session

session = "xC4tHoSZQVSHpVtnHUONYb/obAA=?USER_TOKEN=UycuZUp3Rndja1JnREFJQU1CZThwWVpqbkRWNHZpQW9QMlg0TzY5ZXN4MU5rTlZOaEM5RERuczBCRkRqSHFDY0YxTGZMSUM3WlNHdkxhZEpJUjZXcjh4ekZyUEQ5aUxFMEEuVGt0V3RqdTFKblVBVzV2SnRpSjd3M0NJZFdRJwpwMQou"

I am using angular.js cookies to retrieve the value but it gives me nothing.

console.log('token - ' + $cookieStore.get('USER_TOKEN'));

How can I access the value of USER_TOKEN using Javascript?

I have a secured flask session

session = "xC4tHoSZQVSHpVtnHUONYb/obAA=?USER_TOKEN=UycuZUp3Rndja1JnREFJQU1CZThwWVpqbkRWNHZpQW9QMlg0TzY5ZXN4MU5rTlZOaEM5RERuczBCRkRqSHFDY0YxTGZMSUM3WlNHdkxhZEpJUjZXcjh4ekZyUEQ5aUxFMEEuVGt0V3RqdTFKblVBVzV2SnRpSjd3M0NJZFdRJwpwMQou"

I am using angular.js cookies to retrieve the value but it gives me nothing.

console.log('token - ' + $cookieStore.get('USER_TOKEN'));

How can I access the value of USER_TOKEN using Javascript?

Share Improve this question asked May 1, 2013 at 4:41 daydreamerdaydreamer 92.2k204 gold badges473 silver badges750 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

I could be pletely contradicted on this, but I've been of the understanding that you can't access the session data with Javascript because of some of the internals that the Werkzeug secure cookie module uses. I've got plans to try out this snippet as a workaround:

http://flask.pocoo/snippets/51/

But until I get a chance to try it I wouldn't know whether or not it could do some of the things lacking with the basic session module of Flask.

Since the question was asked Flask switched to itsdangerous client side sessions by default.

As this is still the top google result for this question and i had some problems figuring it out myself, here is how to do it nowadays:

function parse_session(){
    var cookie = Cookies('session');
    if(! cookie) return;
    // Is the content ziped ?
    var un_64 = "";
    if(cookie[0] == "."){
        var data = cookie.split('.')[1].replace(/_/g, '/').replace(/-/g, '+');
        un_b64 = atob(data);
        un_b64 = pako.inflate(un_b64, {to: 'string'});
    }else{
        var data = cookie.split('.')[0].replace(/_/g, '/').replace(/-/g, '+');
        un_b64 = atob(data);
    }
    return jQuery.parseJSON(un_b64);
}

This snippet uses jquery, cookie.js and paco (to unzip). Flasks 'SESSION_COOKIE_HTTPONLY' config variable need to be set to False to be able to read the session on the client side.

Alright. for accessing the cookie session which is set by the flask. we can't directly access in js using document.cookies as it HttpOnly. However, you can access it using the template engine syntax.

let session = {{session|tojson}};
发布评论

评论列表(0)

  1. 暂无评论