typestar

Sessions in Python

A Session is a unit of work: add, flush, commit or roll back.

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column


class Base(DeclarativeBase):
    pass


class Run(Base):
    __tablename__ = "runs"
    id: Mapped[int] = mapped_column(primary_key=True)
    lang: Mapped[str]
    tpm: Mapped[float]


engine = create_engine("sqlite+pysqlite:///:memory:")
Base.metadata.create_all(engine)

with Session(engine) as session:
    session.add_all([Run(lang="python", tpm=104.0), Run(lang="rust", tpm=98.0)])
    session.commit()

    fetched = session.get(Run, 1)
    print(fetched.lang, fetched.tpm)
    fetched.tpm = 110.0
    session.commit()
    print(session.get(Run, 1).tpm)

How it works

  1. add stages an object; commit writes and expires it.
  2. Session.get fetches by primary key.
  3. The context manager closes the session on the way out.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
625
Tokens
163
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 89 seconds.

Type this snippet

Step 3 of 5 in SQLAlchemy, step 15 of 19 in Web services & data access.

← Previous Next →