2

I have seen the other questions so I am going to jump straight to the point.

My website is a blog built with flask, so of course I do operations like updating user info, adding new uploaded files etc.

I always did those operations using app.db, sometimes however I get the error in the title, usually after a few minutes of inactivity.

By looking at the other questions I found out that the best way to handle this is by using the contextmanager session_scope() as shown here:

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = db.Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

What I am unsure about is where I should use this session_scope(). For example, here I update the users bio (description), with the data being POSTed through ajax (this works fine):

description = content['description']
description = (description[:max_characters_allowed_bio]) \
    if len(description) > max_characters_allowed_bio else description

if current_user.description.split() != description.split():
    current_user.description = description
    db.session.commit()

Now, here if I'm correct I should use the session_scope, as I'm doing operations with the database, however I tried this without success:

with session_scope() as session:
    description = content['description']
    description = (description[:max_characters_allowed_bio]) \
        if len(description) > max_characters_allowed_bio else description

    if current_user.description.split() != description.split():
        session.query(User).filter_by(id=current_user.id).description = description
        session.commit()

How would I update this information through the session_scope?

And again, should I use the session_scope only when committing? Or do I need to use it for other queries like these?

Work.query.get_or_404(work_id)
Media.query.filter(Media.path.contains(path)).first().id
G. Ramistella
  • 1,327
  • 1
  • 9
  • 19

0 Answers0