[Python] SQLAlchemy: session.close() or session.commit()

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    And now I need to query some data, as follows:

    def get_xx():
    sess = Session()
    return sess.query(xx).filter(
    xx.id == 3, xx.status == 1
    ).first()


    The isolation level is repeatable read and autocommit is off; So I always get the same result even the value has been updated.

    And now, the question occur, sess.close() and sess.commit(), which method should I use?

    The final solution I attempt to use as follows, however I am not sure if it is good enough (close after commit)?

    @contextmanager
    def auto_session():
    sess = Session()
    try:
    yield sess
    sess.commit()
    except: # swallow any exception
    sess.rollback()
    finally:
    sess.close()


    And the source code changed

    def get_xx():
    with auto_session() as sess:
    return sess.query(xx).filter(
    xx.id == 3, xx.status == 1
    ).first()

    Continue reading...

Compartilhe esta Página