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 stored_titles(titles):
app, db, Role = make_store()
with app.app_context():
db.session.add_all(Role(title=title) for title in titles)
db.session.commit()
statement = select(Role).order_by(Role.id)
return [role.title for role in db.session.scalars(statement)]- Reasoning
- The factory always creates an owned SQLite in-memory database and one Role table. The helper enters the application context, stages supplied rows, commits them and reads an explicitly ordered statement.