from dateutil import parser import utils from models import Zebra, Base, WateringHole from utils import Session, now, DAY Base.metadata.create_all(utils.engine) session = Session() session.add(Zebra(name='Stevie', when_born=parser.parse('2016-04-01'))) session.add( Zebra(name='Anya', when_born=parser.parse('2018-06-05'), number_of_stripes=73, when_stripes_counted=now() - 14 * DAY)) session.add( WateringHole( name="Ol' Watering Hole", # There are no watering holes in Berlin but Weißensee is pretty cool latitude=52.554133, longitude=13.463599, )) session.commit()
assert inspect(zebra).detached zebra.number_of_stripes = 63 session.commit() other_session = Session() # Reload the zebra in a different session zr = other_session.query(Zebra).filter(Zebra.id == zebra.id).one() print(f'{zr.name} has {zr.number_of_stripes} stripes') with silence(): session.close() other_session.close() with step(): session = Session() janet = Zebra(name='Janet', when_born=parser.parse('2018-06-05')) session.add(janet) session.flush() # ID should have been set when we flushed Janet to the database, # which indicates that she was correctly saved. assert janet.id session.expunge(janet) session.commit() print(f"Hi {janet.name}, we're glad you're still here!") # NOTE rollback with step(): session = Session() [za, zb] = session.query(Zebra).limit(2) session.close() assert inspect(za).detached assert inspect(zb).detached