def create_records(): session = create_session() account1 = Account(name='account1', amount=Decimal('11.11')) account2 = Account(name='account2', amount=Decimal('22.22')) session.add(account1) session.add(account2) session.commit()
def first_flow(print_function): session = create_session() print_function('Adding account 3...') account3 = Account(name='account3', amount=Decimal('33.33')) session.add(account3) print_function('Flushing changes to the DB...') session.flush() print_function('Sleeping...') sleep(5) print_function('Waking up...') print_function('We didn\'t commit anything...')
def first_flow(print_function): session = create_session() print_function('Adding account 3...') account3 = Account(name='account3', amount=Decimal('33.33')) session.add(account3) print_function('Flushing changes to the DB...') session.flush() print_function('Sleeping...') sleep(5) print_function('Waking up...') print_function('Rolling back...') session.rollback() print_function('Rolled back!!')
def second_flow(print_function): session = create_session() print_function('Adding new account at the meantime...') account3 = Account(name='account3', amount=Decimal('33.33')) session.add(account3) account1 = session.query(Account).filter(Account.name == 'account1').one_or_none() account2 = session.query(Account).filter(Account.name == 'account2').one_or_none() if account1: print_function('Updating existing account at the meantime...') account1.name = 'Updated from second flow' session.commit() if account2: print_function('Deleting existing account at the meantime...') session.delete(account2) session.commit() print_function('Committed!!')
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from account_model import Account from common import print_first connecting_string = f'mysql+mysqldb://root:[email protected]:52000/lunch_and_learn' engine = create_engine(connecting_string, echo=True, connect_args={'connect_timeout': 10}) Session = sessionmaker(bind=engine, autoflush=True) session = Session() account1 = Account(name='account1', amount=Decimal('11.11')) account2 = Account(name='account2', amount=Decimal('22.22')) session.add(account1) session.add(account2) session.flush() # session.query(Account).count() print_first('Sleeping..') sleep(7) print_first('Waking up!') print_first('Committing...') session.commit() print_first('Committed')