0

In my flask app, I store an instance of a user object in the session

session["user"] = user #Where user is an object

I found out that when updating the object stored in the session directly and commit, the changes are not reflected in the database.

However, I found that when updating the database object directly, the changes are reflected in the database while the session object is unchanged.

If I try a method like

user.username = username
user.password = password
db.commit() #I called my database session 'db', probably not a good idea but not the point
session["user"] = user

it throws:

sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed

What could be a possible solution to update the database correctly and reflect the changes to the flask session? Thanks in advance.

3
  • Are you using the flask-login extension or just plain flask? Commented Oct 8, 2019 at 10:40
  • Is session the database session or a normal dict? Commented Oct 8, 2019 at 10:41
  • 1
    I'm using plain flask and session in this case is the dictionary for flask-session not the database session Commented Oct 8, 2019 at 10:46

1 Answer 1

3

Try setting {'expire_on_commit': False} like,

db = SQLAlchemy(app, session_options={

    'expire_on_commit': False

})
Sign up to request clarification or add additional context in comments.

1 Comment

you are missing an equals sign here session_options{. It should be session_options = {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.