Complete worked example
python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select, String
from sqlalchemy.orm import Mapped, mapped_column
def make_store():
app = Flask(__name__)
app.config.update(TESTING=True, SQLALCHEMY_DATABASE_URI='sqlite:///:memory:')
db = SQLAlchemy(app)
class Role(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(20), nullable=False)
with app.app_context():
db.create_all()
return app, db, Role
def transaction_result(fail):
app, db, Role = make_store()
with app.app_context():
try:
db.session.add(Role(title='API'))
db.session.flush()
if fail:
raise ValueError('controlled failure')
db.session.commit()
except ValueError:
db.session.rollback()
return list(db.session.scalars(select(Role.title).order_by(Role.id)))- Reasoning
- The helper creates one owned database, stages a row and flushes so the write really reaches the transaction. A controlled exception then either triggers rollback or allows commit.