Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flask session to store dict

Tags:

python

flask

As a follow-up on an earlier question, I wonder how to use flask.g and flask.session to transfer a dictionary from one function to another. If I understand g correctly, it only temporarily stores info until a new request. Since the function I want to transfer the dict object to, starts with a new request (it loads a new flask template), I guess I cannot use g. So, this leaves me to wonder whether I can use flask.session for this. If I try to save my dict as follows: session.dict, and then try to use this dict in a new function, it returns an "AttributeError: 'FileSystemSession' object has no attribute 'dict'.

Any idea whether the saving of a dict in a flask session is at all possible? And if so, what am I doing wrong?

like image 996
Bart Koolhaas Avatar asked Dec 19 '22 06:12

Bart Koolhaas


1 Answers

Session in flask is a dictionary. So if you need to save anything in session you can do this:

from flask import session
...

def foo(...):

    session['my_dict'] = my_dict


def bar(...):

    my_dict = session['my_dict']

Note that you need to check whether the my_dict is present in session before trying to use it.

like image 67
Nurjan Avatar answered Dec 21 '22 11:12

Nurjan