pythonsqlalchemyflask-sqlalchemy-lite

Session management in Flask-SQLAlchemy-Lite


I'm moving from vanilla SQLAlchemy to Flask-SQLAlchemy-Lite.

What is the best practice for session management? Can I still do something like this:

    with db.session as session, session.begin():

if I want the block to automatically commit?


Solution

  • Can I still do something like this:

    Yes, that appears to work just fine.

    with app.app_context():
        Base.metadata.create_all(db.engine)
    
        db.engine.echo = True
    
        db.session.add(User(username="example", rev=0))
        db.session.commit()
        """
    INSERT INTO user (username, rev) VALUES (?, ?)
    [generated in 0.00080s] ('example', 0)
    COMMIT
        """
    
        with db.session as sess, sess.begin():
            u = sess.get(User, 1)
            u.rev += 1
            
        """
    UPDATE user SET rev=? WHERE user.id = ?
    [generated in 0.00083s] (1, 1)
    COMMIT
        """