Middle
Did you write the service that applies these transactions? What exactly did it do?
sobes.tech AI
Answer from AI
Yes, I wrote a service in Python that used transactions to ensure data integrity when working with a database. For example, the service processed orders in an online store: when creating an order, it was necessary to simultaneously deduct the item from the stock and record the order information. To avoid data inconsistency, operations were wrapped in a transaction — if something went wrong, all changes were rolled back.
An example using SQLAlchemy:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://user:password@localhost/db')
Session = sessionmaker(bind=engine)
session = Session()
try:
# deduct the product from stock
product = session.query(Product).filter_by(id=product_id).one()
product.stock -= quantity
# create an order
order = Order(user_id=user_id, product_id=product_id, quantity=quantity)
session.add(order)
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
Thus, the service guaranteed that either all operations would be applied or none.