Skip to content
Aabha AI Academy

Module 3 of 9 · Lesson 5 of 26

Give each request its own PostgreSQL session

Work through give each request its own PostgreSQL session using a runnable reference, a focused regression check and a local extension.

Read in any order. All lessons stay open, including after an unanswered or incorrect check.

In this lesson you will give each request its own PostgreSQL session. Work with the Equipment Rental API in the downloadable lab. The reference is a complete solution with separate lesson checks, so you can inspect the answer, make a deliberate local change and verify its behavior.
An engine manages database connections; a session manages one unit of ORM work. Reuse an engine and session factory, but create a session for each request. The sync_session dependency opens a session with a context manager, yields it and closes it even when the route fails. A global mutable session would combine identities, pending changes and rollback state from unrelated requests.

Session lifetime and transaction lifetime are related but different. A SELECT may automatically begin a transaction. A service that owns its write transaction must not blindly begin another one on a session that already has an identity lookup in progress. The reference finishes that read transaction before handing the synchronous write to its service. Commit belongs inside the write boundary and must finish before success is sent. The dependency does not commit after yield. Depends with function scope also ends its resources before the response is sent. A session close releases resources; it cannot turn an uncommitted write into a confirmed success.
Worked source: equipment/api.py, create_app.

Read sync_factory, sync_session and equipment_create in api.py. The lesson05 check opens two sessions at once, flushes a new item in the first, and confirms the second cannot see the uncommitted row. The first session then rolls back. This demonstrates transaction isolation using PostgreSQL, rather than two dictionaries.
pythonCopyable
def test_lesson05(db):
    factory, _ = db
    with factory() as first, factory() as second:
        assert first is not second
        first.add(Equipment(name="Uncommitted", quantity=1, daily_rate="1"))
        first.flush()
        assert (
            second.scalar(select(Equipment).where(Equipment.name == "Uncommitted"))
            is None
        )
        first.rollback()
TerminalPython 3.13 virtual environment; Docker running; extracted lab directory
python run_checks.py -k lesson05

Expected result The selected lesson test passes against a new temporary PostgreSQL database; the container is removed afterward.

Keep for reference

Equipment Rental lab and lesson checks

ZIP containing Python source, real Alembic migrations, 26 lesson checks, a dependency lock and text instructions. Extract it before following the local exercise.

Download Equipment Rental lab and lesson checks

Practise locally

Write a dependency in a small router that opens and closes a session from a shared factory. Add a request test that raises inside the route, then performs a successful read in a new request. Record the two different session identities without exposing a URL or password. Explain why the factory is reusable while the session is owned by one request.

The lesson check verifies the reference behavior. Add your own assertions for your change. Local practice is not uploaded or scored by this learning release.

Pause and reflect

What failure does this lesson prevent, and which assertion in lesson05 would expose it?

Use a concrete input, expected result and limitation from your local work. Saving a reflection does not certify the project.

Optional knowledge check

Which object should normally be shared across requests?

One mutable ORM session containing every request’s changes.

Try another answer. A shared session mixes transaction state and can roll back or commit another request’s work.

Create a new database engine for every query.

Try another answer. Reuse the connection manager and create request-owned sessions instead.

The engine or session factory, with a new session per request.

Correct. Factories provide fresh units of work while the engine manages the connection pool.

This practice does not assess your project or award a certificate.

Your reading progress

Progress is saved in this browser when storage is available.

Sign in to save across devices · Create an optional account