Bart Koolhaas
Bart Koolhaas

Reputation: 351

Using flask session to store dict

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?

Upvotes: 4

Views: 12965

Answers (1)

Nurjan
Nurjan

Reputation: 6053

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.

Upvotes: 11

Related Questions