flask-sqlalchemy-session icon indicating copy to clipboard operation
flask-sqlalchemy-session copied to clipboard

Can you provide an example of how to commit and revert ?

Open fwachs opened this issue 9 years ago • 4 comments
trafficstars

fwachs avatar Apr 13 '16 14:04 fwachs

This is just an SQLAlchemy session object, you can use everything documented at SQLAlchemy's session documentation, which contains a lot of examples.

dtheodor avatar Apr 13 '16 14:04 dtheodor

I understand. Is it ok if I use it like this?

from flask_sqlalchemy_session import current_session
from contextlib import contextmanager

@contextmanager
def session_scope():
    s = current_session
    try:
        yield s
        s.commit()
    except:
        s.rollback()
        raise
def save(self, building):
        with session_scope() as current_session:
            current_session.add(building)
            return building.id

I assume flask-sqlalchemy-session will do the s.close() when the flask request is fulfilled. Right?

fwachs avatar Apr 13 '16 17:04 fwachs

Yes. Also check http://docs.sqlalchemy.org/en/rel_1_0/orm/contextual.html

Btw, the s.rollback() you do might fail with an exception and eat up the original exception, you may want to ignore the new exception

dtheodor avatar Apr 13 '16 19:04 dtheodor

Perfect!

About the s.rollback(), should I wrap it with try except pass ?

fwachs avatar Apr 13 '16 22:04 fwachs